Tutorial :PHP conditional string replacement



Question:

I'm trying to replace the ~ into | between the [ ] in the folowwing case:

{stackoverflow is a [cool~great~fast] website ~ Find your answers [easily~quickly] on stackoverflow}.  

Note: The text between the [ ] can be multiline.

I've tried multiple regexs buth with no luck.

My closest call at the moment is:

$text = preg_replace("/\[(.*?)~(.*?)\]/i", "[$1|$2]", $text);  

But that returns

{stackoverflow is a [cool~great|fast] website ~ Find your answers [easily|quickly] on stackoverflow}.  


Solution:1

You need to use one regex to find all strings in brackets and then another to replace the ~s in them. You can use preg_replace_callback to apply the ~-replacing regex to all the substrings in brackets like this:

preg_replace_callback('/\[[^\]]+\]/', function ($str) {      return str_replace('~', '|', $str[0]);  }, $my_string)  


Solution:2

simpler than you think

 echo preg_replace('/~(?=[^\[\]]*\])/s', '|', $a);  

?= is a lookahead assertion and reads "followed by". That is, "a tilde followed by some non-brackets and then a closing bracket" - this matches only ~'s inside [ ]


Solution:3

What are some examples of the regexes you've used? My immediate thought is that [] is tripping you up because that is used to match character classes. If you want to match [ or ] as a literal you must escape it with backslashes: \[ or \].


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »