2012-02-15 106 views
0

我想使用preg_replace结合'[',']'和'/',但我无法找到正确的方法!preg_replace和组合'[',']'和'/'替换

我有这些字符串:

$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"; 

在结果我想有:

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>."; 

并且还[U] = [U],[/ U] = [/ U]是不区分大小写。

+0

您无法使用preg_replace来平衡标签。 – 2012-02-15 11:22:36

+0

...不仅仅带有'preg_replace'。 – Gumbo 2012-02-15 11:26:51

回答

1

假设没有开口方括号内的[u]标签内:

preg_replace('~\[u\]([^[]+)\[/u\]~i', '<a href="'.$url.'">$1</a>', $str); 

正则表达式说明:

  • ~被用作分隔符,以避免leaning slash syndrome
  • \[\]匹配文字方括号
  • ()表示一个俘获基团,其在替换字符串是$1
  • [^[]+匹配任何不是一个开口括号一次或多次
  • i改性剂使正则表达式不区分大小写。
1

嗯,我想你想要的是

$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\]).)*)意味着它会匹配一些字符,不包括字符串 '[/ U]'

1
$str1 = preg_replace('#\[(u|U)\](.*?)(?=\[/\1)\[/\1\]#', "<a href='http://www.test.com'>$2</a>", $str); 
var_dump($str, $str1); 

输出

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>."