0

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 info@mytext.com

$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?

Duby du
  • 1
  • 1
  • Using a HTML parser (`DOMDocument` for instance). You cannot use regexes to reliably alter HTML. Search for any of the hundreds of the same questions here on SO. – Wrikken Oct 21 '10 at 16:27

3 Answers3

1

A better approach would be to use XML functions instead.

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
0

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
  • 144,265
  • 20
  • 237
  • 291
0

[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('info@mytext.com','[email_safeguard]',$text); 
//work on the text with preg_match()
$text = str_replace('[email_safeguard]','info@mytext.com',$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

Community
  • 1
  • 1
Timo Huovinen
  • 53,325
  • 33
  • 152
  • 143