Forum Moderators: coopster

Message Too Old, No Replies

regular expression

         

bysonary

10:05 am on Jun 17, 2007 (gmt 0)

10+ Year Member



hello

I am in the process of thinking about a regex, to use with preg_replace on a page, for example where the text


[img]imagename.gif[/img]

appears the code will be translated into


<a href="imagename.gif" class="bimg" />

I would appreciate it if someone could help me out, iv never understood regular expression patterns.

Thanks

ahmedtheking

8:26 pm on Jun 17, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Alright, first port of call is this: <snip> and [uk2.php.net...]

Now for your question:

$str = " imagename.gif ";
$new_str = preg_replace("/\[img\](.*)\[\/img\]/","<a href=\"\\1\" class=\"bimg\" />",$str);
echo $new_str;

That should work!

[edited by: eelixduppy at 1:31 am (utc) on June 18, 2007]
[edit reason] removed uri - see forum charter [/edit]

bysonary

10:15 am on Jun 18, 2007 (gmt 0)

10+ Year Member




$str = " imagename.gif ";
$new_str = preg_replace("/\[img\](.*)\[\/img\]/","<a href=\"\\1\" class=\"bimg\" />",$str);
echo $new_str;

That should work!

Hey thanks for that! I have a question relating to part of it though, you see where you have the href in pattern you have..

href=\"\\1\"

what exactly does \1 do? I havent been able to find it in the man pages for php.

any help as to what this does would be great, cheers!

Chris.

Edit: also wouldn't I need a </a> in there?

phranque

10:12 pm on Jun 18, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



what exactly does \1 do? I havent been able to find it in the man pages for php.

that "\1" is a backreference to a captured subpattern.
check a reference on regular expressions [webmasterworld.com] for details.

also wouldn't I need a </a> in there?

eventually - after you print out some anchor content.
the image in the anchor tag is the referenced url, not the content displayed to anchor the link to the image...

bysonary

10:16 pm on Jun 18, 2007 (gmt 0)

10+ Year Member



that url just points to the homepage of WebmasterWorld

if i have two regular expressions would \1 work for both?

phranque

10:46 pm on Jun 18, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



that url just points to the homepage of WebmasterWorld

sorry - i accidentally copied the indirected link.
it's the same link used in an earlier post in this thread:
[uk2.php.net...]

it's too complicated to describe here, so search for "back reference" in the above document and it's all there...

bysonary

11:46 am on Jun 19, 2007 (gmt 0)

10+ Year Member



nice cheers mate you helped me out there :-)