Замена всех пробелов внутри <a>тегов - PullRequest
0 голосов
/ 16 июля 2010

Я боролся с этим некоторое время, так что, надеюсь, кто-нибудь может мне помочь. Мне нужно использовать регулярное выражение для замены всех пробелов внутри тега привязки, например.

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 ]

1 голос
/ 16 июля 2010

Мы имеем дело с регулярным выражением и 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
0 голосов
/ 16 июля 2010
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'
);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...