PHP preg_replace weirdness with custom urls
I'm using the following code to add <span>
tags behind <a>
tags.
$html = preg_replace("~<a.*?href=\"$url\".*?>.*?</a>~i", "$0<span>test</span>", $html);
The code is working fine for regular links (ie. http://www.google.com/), but it will not p开发者_如何学Goerform a replace when the contents of $url are $link$/3/
.
This is example code to show the (mis)behaviour:
<?php
$urls = array();
$urls[] = '$link$/3/';
$urls[] = 'http://www.google.com/';
$html = '<a href="$link/3/">Test Link</a>' . "\n" . '<a href="http://www.google.com/">Google</a>';
foreach($urls as $url) {
$html = preg_replace("~<a.*?href=\"$url\".*?>.*?</a>~i", "$0<span>test</span>", $html);
}
echo $html;
?>
And this is the output it produces:
<a href="$link$/3/">Test Link</a>
<a href="http://www.google.com/">Google</a><span>test</span>
$url = preg_quote($url, '~');
the dollar signs are interpreted as usual: end-of-input.
just somebody is correct; you must escape your special regex characters if you mean for them to be interpreted as literal.
It also looks to me like it can't perform the replace because it never makes a match.
Try replacing this line:
$urls[] = '$link$/3/';
With this:
$urls[] = '$link/3/';
$
is considered a special regex character and needs to be escaped. Use preg_quote()
to escape $url
before passing it to preg_replace()
.
$url = preg_quote($url, '~');
$ has special meaning in regex. End of line. Your expression is being expanded like this:
$html = preg_replace("~<a.*?href=\"$link$/3/\".*?>.*?</a>~i", "$0<span>test</span>", $html);
Which fails because it can't find "link" between two end of lines. Try escaping the $ in the $urls array:
$urls[] = '\$link\$/3/';
精彩评论