Reputation: 243
I want to use preg_replace for combination of '[', ']' and '/' but I could'nt find the right way!
I have these strings:
$str = "This is a [u]PHP[/u] test . This is second[/u] test.
This [u]is another [u]test[/u].";
$url = "http://www.test.com";
In result I want to have :
str1 = "This is a <a href='http://www.test.com'>PHP</a> test .
This is second[/u] test.
This <a href='http://www.test.com'>is another [u]test</a>.";
and also [u]=[U], [/u]=[/U] are case insensitive.
Upvotes: 0
Views: 1201
Reputation: 913
Well,i think what you want is
$str = "This is a [u]PHP[/u] test . This is second[/u] test.
This [u]is another [u]test[/u].";
$url = "http://www.test.com";
echo preg_replace('#\[u\]((?:(?!\[/u\]).)*)\[/u\]#is',"<a href='{$url}'>\\1</a>",$str);
((?:(?!\[/u\]).)*)
means it would match some characters which don't including string '[/u]'
Upvotes: 1
Reputation: 57650
$str1 = preg_replace('#\[(u|U)\](.*?)(?=\[/\1)\[/\1\]#', "<a href='http://www.test.com'>$2</a>", $str);
var_dump($str, $str1);
Output
string(85) "This is a [u]PHP[/u] test . This is second[/u] test.
This [u]is another [u]test[/u]."
string(139) "This is a <a href='http://www.test.com'>PHP</a> test . This is second[/u] test.
This <a href='http://www.test.com'>is another [u]test</a>."
Upvotes: 1
Reputation: 34632
Assuming no opening square brackets inside the [u]
tags:
preg_replace('~\[u\]([^[]+)\[/u\]~i', '<a href="'.$url.'">$1</a>', $str);
The regular expression explained:
~
is used as delimiter to avoid leaning slash syndrome\[
and \]
match literal square brackets(
and )
denote a capture group which in the replacement string is $1
[^[]+
matches anything but an opening square bracket once or morei
modifier makes the regular expression case insensitive.Upvotes: 1