Skip to content

Instantly share code, notes, and snippets.

@brynbellomy
Created July 1, 2011 21:07
Show Gist options
  • Save brynbellomy/1059399 to your computer and use it in GitHub Desktop.
Save brynbellomy/1059399 to your computer and use it in GitHub Desktop.
Regex search and replace text within an HTML document that is not part of a tag
/**
* the [^<i] at the end of the first capture prevents the regex from catching strings
* that are actually part of other strings or tags. Replace the 'i' with anything that
* shouldn't come before the text to be captured. Example: capture 'nSPEC' but not
* 'inspect' -- hence the 'i'.
*
* the [^™] in the third capture does similarly for what comes after the text to be captured.
*/
$input = preg_replace('/>(?P<before>[^<]*?[^<i])?(?P<theText>The text goes here)(?P<char>[^™])/i', ">$1<span class=\"nspec\">$2™</span>$3", $input);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment