Desmond Liang
Desmond Liang

Reputation: 2310

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 2'>STRING1</a>

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

Upvotes: 1

Views: 401

Answers (4)

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

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)

Upvotes: 0

jabbany
jabbany

Reputation: 529

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

Upvotes: 0

Kodiak
Kodiak

Reputation: 5978

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

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190943

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

Upvotes: 5

Related Questions