开发者

Replacing all spaces inside <a> tags

I've been struggling with this for a while now so hopefully someone can help me out. I need to use regex to replace all spaces inside an anchor tag for example.

Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all
开发者_StackOverflow中文版

Needs to become

Hello this is a string, check this <a[SPACE]href="http://www.google.com">Google[SPACE]is[SPACE]cool</a> Oh and this <a[SPACE]href="http://www.google.com/blah[SPACE]blah">Google[SPACE]is[SPACE]cool</a> That is all


We're dealing with regex and XMLish string - though the following works for the given test case, your mileage might vary for a different test case; use carefully.

<?
function replace($matches)
{
        return preg_replace("/ /", "[SPACE]", $matches[0]);
}
$s = 'Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all';
echo "Before::......\n\n$s\n\nAfter::......\n\n";
echo preg_replace_callback('#<a\b(.+?)</a>#', 'replace', $s);
echo "\n";
?>

Output

Before::......

Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all

After::......

Hello this is a string, check this <a[SPACE]href="http://www.google.com">Google[SPACE]is[SPACE]cool</a> Oh and this <a[SPACE]href="http://www.google.com/blah[SPACE]blah">Google[SPACE]is[SPACE]cool</a> That is all


preg_replace(
  '/(<a .+?<\/a>)/e',
  'str_replace(" ", "[SPACE]", "\1")',
  'Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all'
);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜