1

I would like to make a replace on a string where I have to have multiple conditions and do the replace based on them. I know I can use array as search string in str_replace() but my problem is that a part of the string is dynamic.

For example:

the string would look like this:

<p>SOME TEXT</p> 
<p>SOME TEXT (dynamic content 1)</p> 
<p>SOME TEXT (dynamic content 2)</p> 
<p>SOME TEXT</p>

and the replaced string should look like this

<p>SOME <span>TEXT</span></p> 
<p>SOME <span>TEXT (dynamic content 1)</span></p> 
<p>SOME <span>TEXT (dynamic content 2)</span></p> 
<p>SOME <span>TEXT</span></p>

As the example shows the search words are TEXT and TEXT (dyn cont) my problem is that I can't figure out how do I set the condition for the second search word where the content is dynamic between the brackets.

Basicly if there were 2 constant words than I would do something like this:

if(strpos($str, 'TEXT') !== FALSE || strpos($str, 'TEXT ()') !== FALSE){
  echo str_replace(array('TEXT', 'TEXT ()'), 
                   array('<span>TEXT</span>', '<span>TEXT ()</span>'),
                   $str);
}
else {
  echo $str;
}

but obviously this doesn't works in this case.

How can I make this work?

1
  • 2
    regexes would do the trick. str_replace can't match wildcards, so unless you do a bunch of searching/locating first, you can't use str_replace for this. Commented Aug 13, 2015 at 19:40

1 Answer 1

2

You can use this regex for matching:

(?:<p>SOME\s)(TEXT\s?.*?)(?:<\/p>)

The single capture group should get TEXT and anything after it up until the </p>

Additionally, if you want to allow that dynamic content to contain newlines, change the regex to this:

(?:<p>SOME\s)(TEXT\s?[\s\S]*?)(?:<\/p>)

Regex101

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I modified your expression a little bit and than did a preg_replace(). Now everething is ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.