Issue
I have this regular expression:
https://regex101.com/r/Eaj73B/5
As you can see it matches group 1 and group 2 from the given string.
But when I use preg_replace in php it replaces not group 2 of the full match:
preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\\?\/\1\])?/', '', $string)
How can I replace the full match?
UPDATE:
In the tester regex101.com the regex works well indeed. But on a real PHP server it doesn't work as expected. See below:
Tested on 2 different servers with php7.2 with this method, but this is the result:
public function TestReplace(){
$string = 'x[embed]some text or url[/embed]x';
return preg_replace('/\[(\w+)[^\]]*]([^\[]+\[\\?\/\1\])?/', '', $string);
}
returns:
xsome text or url[/embed]x
So it only replace [embed] on a real php7.2 server. I really don't know what I do wrong here...
Solution
I found the answer! It seems that php preg_replace does not support some regex functions, so I had to change the regex a bit.
This one works for php:
preg_replace('/\[\w+[^\]]*]([^\[]+\[[\\a-zA-Z\/]+\])?/', '', $string);
With thanks to this post: PHP preg_replace non-greedy trouble.
So my conclusion is also that this live testers like www.phpliveregex.com are not always reliable.
Answered By - brasileric Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.