Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-15-2013, 07:12 PM   PM User | #1
shadkeene
Regular Coder

 
Join Date: May 2007
Posts: 148
Thanks: 6
Thanked 0 Times in 0 Posts
shadkeene is an unknown quantity at this point
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
shadkeene is offline   Reply With Quote
Old 01-15-2013, 08:46 PM   PM User | #2
kbluhm
Senior Coder

 
kbluhm's Avatar
 
Join Date: Apr 2007
Location: Philadelphia, PA, USA
Posts: 1,502
Thanks: 2
Thanked 258 Times in 254 Posts
kbluhm will become famous soon enough
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 ); 
__________________
ZCE

Last edited by kbluhm; 01-15-2013 at 09:34 PM..
kbluhm is offline   Reply With Quote
Old 01-17-2013, 09:20 AM   PM User | #3
gvre
Regular Coder

 
Join Date: May 2011
Posts: 212
Thanks: 1
Thanked 50 Times in 49 Posts
gvre is an unknown quantity at this point
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
gvre is offline   Reply With Quote
Users who have thanked gvre for this post:
shadkeene (02-26-2013)
Old 02-26-2013, 04:39 PM   PM User | #4
shadkeene
Regular Coder

 
Join Date: May 2007
Posts: 148
Thanks: 6
Thanked 0 Times in 0 Posts
shadkeene is an unknown quantity at this point
Thanks very much. That works perfectly!
shadkeene is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:28 PM.


Advertisement
Log in to turn off these ads.