tags:

views:

32

answers:

3

I have this code to do some ugly inline text style color formatting on html content. But this breaks anything inside tags as links, and emails.

I've figured out halfways how to prevent it from formatting links, but it still doesn't prevent the replace when the text is [email protected]

$text = preg_replace('/(?<!\.)mytext(?!\/)/', '<span style="color:#DD1E32">my</span><span style="color:#002d6a">text</span>', $text);

What will be a better approach to only replace text, and prevent the replacing on links?

A: 

A better approach would be to use XML functions instead.

Emil Vikström
A: 

Your lookbehind assertion only tests one character, so it's insufficient to assert matches outside of html tags. This is something where regular expression aren't the best option. You can however get an approximation like:

preg_replace("/(>[^<]*)(?<![@.])(mytext)/", "$1<span>$2</span>",

This would overlook the first occourence of mytext if it's not preceeded by a html tag. So works best if $text = "<div>$text</div>" or something.

mario
A: 

[edited] ohh I see you solved the href problem. to solve your email problem, change all @mytext. to [email_safeguard] with str_replace, before working on the text, and when your finished, change it back. :)

$text = str_replace('[email protected]','[email_safeguard]',$text); 
//work on the text with preg_match()
$text = str_replace('[email_safeguard]','[email protected]',$text); 

that should do the trick :)

but as people have mentioned before, you better avoid html and regex, or you will suffer the wrath of Cthulhu.

see this instead

YuriKolovsky