tags:

views:

64

answers:

2

Hi,

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"&gt;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"&gt;Google[SPACE]is[SPACE]cool&lt;/a&gt; Oh and this <a[SPACE]href="http://www.google.com/blah[SPACE]blah"&gt;Google[SPACE]is[SPACE]cool&lt;/a&gt; That is all

Thank you

+1  A: 

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"&gt;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"&gt;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"&gt;Google[SPACE]is[SPACE]cool&lt;/a&gt; Oh and this <a[SPACE]href="http://www.google.com/blah[SPACE]blah"&gt;Google[SPACE]is[SPACE]cool&lt;/a&gt; That is all
Amarghosh
A: 
preg_replace(
  '/(<a .+?<\/a>)/e',
  'str_replace(" ", "[SPACE]", "\1")',
  'Hello this is a string, check this <a href="http://www.google.com"&gt;Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all'
);
Maerlyn