RegEx: more pattern matching problems

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
grum
Forum Newbie
Posts: 3
Joined: Sat Sep 04, 2004 5:36 pm

RegEx: more pattern matching problems

Post by grum »

Hey guys, I'm a newbie as you can see. Nice site.

Anyway, I'm developing a new site which uses a take on BB Code, but it's slightly different. I've had a read through a lot of RegEx stuff but it really is beyond me right now, so I've had no luck adapting code I've found.

So any help would be great :)

I want to search for URLs prefixed with "image=" and place them inside img tags.

i.e., turn image=http://www.blah.com/blah.gif into <img src="http://www.blah.com/blah.gif" />

Cheers,
Grum
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php

$text = 'image=http://foo.com/bar.gif blahblahblah image=http://foo.com/bar.gif blahblahblah testimage=http://foo.com/bar.png image=http://foo.com/bar.jpg. image=http://foo.com/bar.jpg79';

echo preg_replace('#(?<![\w\d])image=((http|ftp|https|ftps)://[^ \?&=\#"\n\r\t<]*?\.(jpg|jpeg|gif|png))(?![\w\d])#sie', '''<img src="'' . str_replace('' '',''%20'',''\\1'') . ''" border="0" />''', $text);

?>
outputs:

Code: Select all

&lt;img src="http://foo.com/bar.gif" border="0" /&gt; blahblahblah &lt;img src="http://foo.com/bar.gif" border="0" /&gt; blahblahblah &lt;img src="http://foo.com/bar2.jpeg" border="0" /&gt; testimage=http://foo.com/bar.png &lt;img src="http://foo.com/bar.jpg" border="0" /&gt;. image=http://foo.com/bar.jpg79
grum
Forum Newbie
Posts: 3
Joined: Sat Sep 04, 2004 5:36 pm

Post by grum »

Yep that works for me, cheers!

I've got this URL autolinking code....

Code: Select all

<?php
$temp = ereg_replace("[[]]+://[^<>[]]+[[]/]",
"<a href="\\0" target="_blank">\\0</a><div class="new_window">&nbsp;(Opens in new window)&nbsp;</div>\n", $temp);
?>
But I need a wee snippet to stop it taking URLs in tags, by for example not takings URLs prefixed with quote marks, i.e., ...src="http://....

Sounds so simple, but what would you insert at the start of the RegEx statement?

Any tips on learning this stuff?

Grum
grum
Forum Newbie
Posts: 3
Joined: Sat Sep 04, 2004 5:36 pm

Post by grum »

Code: Select all

<?php
$temp = ereg_replace("[[]]+[[]]+://[^<>[]]+[[]/]", "<a href="\\0" target="_blank">\\0</a><div class="new_window">&nbsp;(Opens in new window)&nbsp;</div>\n", $temp);
?>
Solved my problem, it'll now take only URLs preceded by a space. Progress I think! Hehe.

Anyway, thanks for your help.
Post Reply