Page 1 of 1

My Favorite Multi-Purpose Regex

Posted: Sat Nov 29, 2008 6:00 pm
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.

Re: My Favorite Multi-Purpose Regex

Posted: Sun Nov 30, 2008 1:50 pm
by omniuni
This gets me thinking.... is there a simple way to modify this so that it returns the value between the tags?

Re: My Favorite Multi-Purpose Regex

Posted: Sun Nov 30, 2008 1:58 pm
by Syntac
I imagine it would be something like this?

Code: Select all

$s = preg_replace('@<img(.*?)>@s','$1',$s);

Re: My Favorite Multi-Purpose Regex

Posted: Sun Nov 30, 2008 2:30 pm
by mintedjo
volomike wrote:before I learned the @ trick
Whats the @ trick?

Re: My Favorite Multi-Purpose Regex

Posted: Sun Nov 30, 2008 5:53 pm
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.

Re: My Favorite Multi-Purpose Regex

Posted: Mon Dec 01, 2008 2:19 pm
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.

Re: My Favorite Multi-Purpose Regex

Posted: Mon Dec 01, 2008 2:24 pm
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