Laci K
Laci K

Reputation: 595

PHP string replace with multiple conditions

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?

Upvotes: 1

Views: 680

Answers (1)

d0nut
d0nut

Reputation: 2834

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

Upvotes: 2

Related Questions