替换<a> tags</a>内的所有空格

时间:2010-07-16 13:05:17

标签: php regex

我一直在努力解决这个问题,所以希望有人可以帮助我。我需要使用正则表达式替换锚标记内的所有空格,例如。

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

需要成为

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

2 个答案:

答案 0 :(得分:1)

我们正在处理正则表达式和XML格式字符串 - 虽然以下适用于给定的测试用例,但对于不同的测试用例,您的里程可能会有所不同;小心使用。

<?
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";
?>

输出

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

答案 1 :(得分:0)

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'
);