Reputation: 1048
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}.
Upvotes: 0
Views: 1341
Reputation: 53940
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 [ ]
Upvotes: 2
Reputation: 370102
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)
Upvotes: 2
Reputation: 23
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 \].
Upvotes: 0