| preg replace with boundary and array
|
haamro

msg:4366536 | 8:56 pm on Sep 23, 2011 (gmt 0) | Hi there, I am trying to delete words in the sentence contained in an array. I cannot use str_replace, because it replaces that character within another word. (e.g. , if I try to delete "is"; "this" becomes "th") So, I wanted to use preg_replace with boundary, but how do I add "/b" to the array ? ( I don't want to change my array) $ignore=array("is","a","the"); $sentence="this is the way I want"; My output should be = "this way I want" thanx
|
astupidname

msg:4366651 | 8:08 am on Sep 24, 2011 (gmt 0) | Assuming $ignore will never contain special characters which would trip up the regular expression, the below should work out if $ignore is always alphabetic words: $ignore=array("is","a","the"); $sentence="this is the way I want"; //create regular expression, using the items in $ignore, //which in this case the regular expression will look like: /\b(is|a|the)\b/ $rex = '/\b('.implode('|', $ignore).')\b/'; echo preg_replace($rex, '', $sentence); |
| Note you may want to add an 'i' modifier to make $rex case insensitive: | $rex = '/\b('.implode('|', $ignore).')\b/i'; |
|
|
haamro

msg:4366683 | 12:08 pm on Sep 24, 2011 (gmt 0) | Works like a charm ! Thanx for your help :-)
|
haamro

msg:4366700 | 2:16 pm on Sep 24, 2011 (gmt 0) | * Sorry couldn't update previous post. Thanx astupidname, what if $ignore has unicode character, real unicode word (not अअ) /i/u didn't work for me.
|
penders

msg:4367460 | 6:32 pm on Sep 26, 2011 (gmt 0) | This should be: /iu
|
haamro

msg:4369383 | 1:54 am on Oct 1, 2011 (gmt 0) | thanx, that worked ! but how do I use \b with /iu ?
|
penders

msg:4369448 | 8:12 am on Oct 1, 2011 (gmt 0) | You should just be able to use them together, as in Readie's code above. Or are you finding that it's not working? The "/" delimits the regular expression (regex). The "iu" are pattern modifiers and appear after the regex. The "\b" is an escape sequence that appears inside the regex and matches a word boundary (the position between a word and a non-word character). So, in Readie's code, this becomes... $rex = '/\b('.implode('|', $ignore).')\b/iu'; |
|
|
Readie

msg:4369529 | 2:32 pm on Oct 1, 2011 (gmt 0) | | as in Readie's code above |
| :/ I didn't post here :P | Assuming $ignore will never contain special characters which would trip up the regular expression |
| You can get around this by using the preg_quote() function [uk3.php.net...] $rex = '/\b('.preg_quote(implode('|', $ignore)).')\b/'; |
|
|
penders

msg:4369539 | 3:20 pm on Oct 1, 2011 (gmt 0) | lol, sorry! :& I think I must have been flitting between different threads!? I meant "astupidname's code above"...!
|
|
|