开发者

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

开发者 https://www.devze.com 2023-03-21 04:14 出处:网络
How do I write a preg_replace string that convert: \"[[ STRING1 | STRING 2 ]]\" to <a href=\'STRING 开发者_如何学Go2\'>STRING1</a>

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

精彩评论

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