954,580 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

preg_replace() to remove words beginning with a pattern

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!

cscgal
The Queen of DaniWeb
Administrator
19,432 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
 

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

echo $r;

MaybeS
Newbie Poster
4 posts since Oct 2011
Reputation Points: 23
Solved Threads: 1
 

What is TIA?

MaybeS
Newbie Poster
4 posts since Oct 2011
Reputation Points: 23
Solved Threads: 1
 

TIA = Thanks In Advance

Zagga
Posting Whiz in Training
257 posts since Dec 2009
Reputation Points: 22
Solved Threads: 54
 

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

cscgal
The Queen of DaniWeb
Administrator
19,432 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
 

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

MaybeS
Newbie Poster
4 posts since Oct 2011
Reputation Points: 23
Solved Threads: 1
 

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.

cscgal
The Queen of DaniWeb
Administrator
19,432 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
 

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:

MaybeS
Newbie Poster
4 posts since Oct 2011
Reputation Points: 23
Solved Threads: 1
 

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

cscgal
The Queen of DaniWeb
Administrator
19,432 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
 

http://www.codeproject.com/KB/dotnet/regextutorial.aspx

I couldn't get my head around them either until I found this site. Nice non-techie speak. Even a muddlehead like me can understand it.

diafol
Rhod Gilbert Fan (ardav)
Moderator
7,792 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: