My Favorite Multi-Purpose Regex

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
volomike
Forum Regular
Posts: 633
Joined: Wed Jan 16, 2008 9:04 am
Location: Myrtle Beach, South Carolina, USA

My Favorite Multi-Purpose Regex

Post by volomike »

This has turned out to be my favorite multi-purpose regex. I thought I'd share it:

Code: Select all

$s = preg_replace('@<img.*?>@s','',$s);
In the above example, it looks for all occurrences of <img and ending with > and replaces them with the second parameter, which, in this case, is nothing. The .*? means "all characters between".

You see, before I learned the @ trick, I was having trouble getting my regex's to not assume characters I was typing were part of the regex.
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: My Favorite Multi-Purpose Regex

Post by omniuni »

This gets me thinking.... is there a simple way to modify this so that it returns the value between the tags?
User avatar
Syntac
Forum Contributor
Posts: 327
Joined: Sun Sep 14, 2008 7:59 pm

Re: My Favorite Multi-Purpose Regex

Post by Syntac »

I imagine it would be something like this?

Code: Select all

$s = preg_replace('@<img(.*?)>@s','$1',$s);
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Re: My Favorite Multi-Purpose Regex

Post by mintedjo »

volomike wrote:before I learned the @ trick
Whats the @ trick?
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: My Favorite Multi-Purpose Regex

Post by Kieran Huggins »

He's using the @ symbol as the regex delimiter - in PHP you can use (almost?) any symbol for convenience. The default symbol "/" is often a pain, since you then have to escape every literal / in your regex.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: My Favorite Multi-Purpose Regex

Post by prometheuzz »

Kieran Huggins wrote:He's using the @ symbol as the regex delimiter - in PHP you can use (almost?) any symbol for convenience ...
Any character except alphanumerics and backslashes can be used.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: My Favorite Multi-Purpose Regex

Post by prometheuzz »

volomike wrote:...

Code: Select all

$s = preg_replace('@<img.*?>@s','',$s);
...
You could improve that regex.
See the paragraph "An Alternative to Laziness" from: http://www.regular-expressions.info/repeat.html
Post Reply