#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2006
    Posts
    18
    Rep Power
    0

    Preg replace only outside HTML tags


    Hi,
    i need to search and replace keywords, but these keywords should not be html tags.

    for example if the user inputs "strong"/ "class", it should replace all "strong" Or "class" with a keyword of my choice, but all html tag <strong> and all attributes "class" should remain as is.


    been trying all combinations but just cant get it .

    Thanks in advance.


    M.
    PS: i want to use preg replace and NOT DOM.
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,068
    Rep Power
    9398
    Do a preg_split() to separate the text into parts that alternate as HTML tags and raw text, and do the rest of the replacing on only the text parts.
    PHP Code:
    $parts preg_split('#</?[a-z][^>]*>#i'$text, -1PREG_SPLIT_DELIM_CAPTURE);
    print_r($parts); 
    I'm too lazy to look up the syntax to make sure I'm right, but I think I am.
  4. #3
  5. Turn left at the third duck
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Location
    Nelson, NZ
    Posts
    112
    Rep Power
    93
    Not to take anything away from requinix's idea, which might be exactly what you need.

    Just another potential direction depending on your inclination: Are you familiar with lookarounds? To give you an example, this regex:
    Code:
    (?!strong>)(?<!<)\bstrong\b
    matches the word "strong" that is neither followed by a ">" nor preceded by a "<".

    Wishing you a fun day
    Last edited by ragax; December 21st, 2011 at 11:59 PM. Reason: Improved punctuation.

IMN logo majestic logo threadwatch logo seochat tools logo