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


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


$s = 'site:mysite.com something';
$r = preg_replace('/site([\S]+)/', '', $s);

echo $r;

commented: Thanks, that worked! +13

TIA = Thanks In Advance

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 ;)

On a scale from 1 to 10 this is 1 - just your super-basic regex pattern.

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.

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:

Ooh thanks. So \S is the same as ^\s ?