0

Hi,

How can I use preg_replace to determine if a string contains a word beginning with a pattern, and if it does, remove it?

Basically I want to capture query strings from a search, but throw away search modifiers. For example, the search query string:

site:daniweb.com query

would just become

query

In this case, I want to remove all words in the string that begin with 'site:'.

TIA!

4
Contributors
9
Replies
10
Views
6 Years
Discussion Span
Last Post by diafol
0

Hi Maybe,

Thanks, that worked. I was doing two things wrong. Firstly, I was missing the beginning and trailing slash. Secondly, I spent a half hour trying to get it to work on the wrong search string ;)

0

Yeah, I'm just REALLLLLY bad with regex. And I haven't done it in quite awhile. Do you always use the forward and trailing slashes? I can't seem to figure out what they are there for. I kept trying to use the ^ and $ to start and end.

1

Actually, this one is "more correct"

$r = preg_replace('/(^|\s)site:([\S]+)/', '', $s);

this makes sure that it actually does begin with site: and not part of another word like mysite:

Edited by MaybeS: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.