Forum Moderators: phranque

Message Too Old, No Replies

Struggling with regular expressions: Redux

Some things need an answer

         

iamzippy

6:34 pm on Mar 16, 2012 (gmt 0)

10+ Year Member



An interesting challenge was posted last 9/11 [webmasterworld.com ]. In that brief exchange, lucy24 hammered home some pretty sophisticated suggestions, which at first made me giddy. But they were good. ;)

OP, however, perhaps unsurprisingly, was last seen heading for the hills. No proper resolution has come out of that thread, to the eternal frustration of countless WebmasterWorld visitors, I've no doubt. This was a question that cried for a solution. Here, if I may, I'd like to offer my own PHP 5.2 mashup.

To paraphrase the original example:

$string = "Lots of text then this bad http:/<!-- www.BestBBS.com -->/example.com/image1.jpg and then this OK http:/<!-- www.BestBBS.com -->/example.local/image2.jpg more text";
$pattern = "/\[img\]http:\/\/(example\.com).+?\[\/img\]/im";
$replacement = '[Images from ${1} not allowed]';
$result = preg_replace( $pattern, $replacement, $string );
echo $result;

It's just a testable example. Don't expect it to revolutionize your site without a bit more effort on your part. Btw, the '/im' modifiers make it case-insensitive and multi-line, so an entire comment, with newlines, can be fed through it.

I needed to flush this. Now I can die in peace.