开发者

preg_replace to replace string that contains "[" and "]"

How do I write a preg_replace string that convert:

"[[ STRING1 | STRING 2 ]]"

to

<a href='STRING 开发者_如何学Go2'>STRING1</a>

in PHP? I having trouble matching the characters "[","]" and "|" as they are reserved.


Use a \ before the symbol to escape them: \[, \] and \|.


Just escape them in your regexp : "[" => "\["


preg_replace('~\[\[(.+)\|(.+)\]\]~iUs','<a href="$2">$1</a>',$string);


As other already said, you have to escape any special characters, using \. You can also use preg_quote to escape the text passed to regular expressions (extremly usefull if you are building dinamic regexps)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜