Log in

View Full Version : Can't use brackets in preg_replace



rctxtreme
08-30-2007, 10:36 PM
$find = array(
"'<a href=\"(.*?)\" title=\"(.*?)\" tabindex=\"(.*?)\">diff</a>'i",
"'<a href=\"(.*?)\" title=\"(.*?)\">hist</a>'i",
);
$replace = array(
"<a href=\"\\1\" title=\"\\2\" tabindex=\"\\3\"><img src=\"http://wprcph.a2h.8m6.net/diff.gif\" alt=\"diff\" /></a>",
"<a href=\"\\1\" title=\"\\2\"><img src=\"http://wprcph.a2h.8m6.net/hist.gif\" alt=\"hist\" /></a>",
);

$out6=preg_replace($find,$replace,$out5);
See that code? It runs perfectly fine.

But it doesn't when I try to do this:

$find = array(
"'(<a href=\"(.*?)\" title=\"(.*?)\" tabindex=\"(.*?)\">diff</a>)'i",
"'(<a href=\"(.*?)\" title=\"(.*?)\">hist</a>)'i",
);
$replace = array(
"<a href=\"\\1\" title=\"\\2\" tabindex=\"\\3\"><img src=\"http://wprcph.a2h.8m6.net/diff.gif\" alt=\"diff\" /></a>",
"<a href=\"\\1\" title=\"\\2\"><img src=\"http://wprcph.a2h.8m6.net/hist.gif\" alt=\"hist\" /></a>",
);

$out6=preg_replace($find,$replace,$out5);
I wish to kill the brackets that surrond the diff and hist links, but as soon as I try the whole layout screws.

Any help?

Twey
08-30-2007, 11:06 PM
Brackets are a special character in regex and must be escaped accordingly:
$find = array(
'/\(<a href="(.*?)" title="(.*?)" tabindex="(.*?)">diff</a>\)/i',
'/\(<a href="(.*?)" title="(.*?)">hist</a>\)/i',
);
$replace = array(
'<a href="$1" title="$2" tabindex="$3"><img src="http://wprcph.a2h.8m6.net/diff.gif" alt="diff"></a>',
'<a href="$1" title="$2"><img src="http://wprcph.a2h.8m6.net/hist.gif" alt="hist"></a>',
);Don't overuse double quotes in PHP. They're slightly less efficient, and often considerably less readable, as seen here. Also, $n is now the preferred way of referencing a capture.