开发者

Find unknown string around my string

I just want to find unknown text around my string between two spaces. For example:

$mystring = "blabalbla <b>sometext</b> <b>ssssss</b>"

What I want to do with this:

I know the "sometext" but I want to put in a string the

<b>sometext</b>.

But my string is always changing, forexample it can be:

<s><b>sometext</b></s>

Now I need to put the whole into a string

<s><b>sometext</b></s>.

So I can't use simply attaching my variable to

<b>.mystring.</b> 

beacuse in cases I can have unknown strings around it.

How can I do this开发者_如何转开发? Or is there another way to find and delete those

<b><s><i></b></s></i> etc....  around my string?

Thnaks, Creep.


You could use a regex:

$mystring = preg_replace('/(^|\s)(?:<[^>]*>)*sometext(?:<[^>]*>)*(\s|$)/i', '$1'.$some_new_text.'$2', $mystring);

I tested this against what you provided, is should work pretty well. It handles the text being on it's own, at the start or end of the string, and surrounded by an unlimited number of html entities.

Description

  • Match either the start of the string, or a space (^|\s)
  • Followed by zero or more html nodes (?:<[^>]*>)*
    • These are in a non-capturing group, so they don't get assigned a group number
  • Followed by the known string
    • If you plan on having this string be dynamic, you will need to use the preg_quote method to escape any special characters
  • Followed by zero or more html nodes (?:<[^>]*>)*
  • Followed by either a space or the end of the string (\s|$)
  • Match case-insensitvely /i (optional)

Notice that the leading and trailing spaces (if any) are added back in on the replacement string $1 and $2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜