Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    May 2007
    Posts
    162
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Parse out word only if it doesn't follow a specific word

    I'm trying to parse out individual key words in a string ($dot_afd). However, in the case of "pass", there's a town named "GRANTS PASS" that I don't want to be included. I only want "PASS" highlighted if it doesn't come after the word "GRANTS".

    I tried some lookbehind code, but unsuccessful. Here's my code that still highlights "PASS" even if it comes after "GRANTS".

    PHP Code:
    $patterns[2] = 'PASS';
    $replacements = array();
    $replacements[2] = '<b><i>PASS </i></b>';
    $dot_afd preg_replace($patterns$replacements$dot_afd); 
    If you have any advice, I would appreciate it. Thanks for your time,

    S

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Quick and dirty... this will work, but there mayyy be a better way:
    PHP Code:
    // highlight ALL instances of `pass`
    $dot_afd preg_replace'/(pass)/i''<b><i>$1</i></b>'$dot_afd );

    // now remove highlighting from instances that follow `grants`
    $dot_afd preg_replace'/(grants)(\s+)\<b\>\<i\>(pass)\<\/i\>\<\/b\>/si''$1$2$3'$dot_afd ); 
    Last edited by kbluhm; 01-15-2013 at 10:34 PM.

  • #3
    Regular Coder
    Join Date
    May 2011
    Posts
    241
    Thanks
    1
    Thanked 57 Times in 56 Posts
    You should use negative lookbehind in your pattern. Try this one

    PHP Code:
    $dot_afd "GRANTS PASS";
    $pattern '#(?<!GRANTS\s)PASS#';
    $replacement '<b><i>PASS </i></b>';
    $dot_afd preg_replace($pattern$replacement$dot_afd);
    echo 
    $dot_afd

  • Users who have thanked gvre for this post:

    shadkeene (02-26-2013)

  • #4
    Regular Coder
    Join Date
    May 2007
    Posts
    162
    Thanks
    13
    Thanked 0 Times in 0 Posts
    Thanks very much. That works perfectly!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •