Not-in-use
Not-in-use

Reputation: 79

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

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

Upvotes: 0

Views: 276

Answers (2)

Maerlyn
Maerlyn

Reputation: 34105

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

Upvotes: 0

Amarghosh
Amarghosh

Reputation: 59451

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

Upvotes: 1

Related Questions