Forum Moderators: coopster

Message Too Old, No Replies

using PERL regex in PHP

How would I do this?

         

adni18

3:00 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi. I'm rather new to PHP, and I need to know how I would go about doing the following:

I have a directory with a bunch of files in it (images). What I want to do is have PHP replace all the tags that look something like

[hi.gif]

with

<img src="emoticons/hi.gif">

but ONLY if the file exists. How could I do the replacement?

Is there some way to reference to a certain grouping of regex stuff, like in perl? ($1)

Please respond ASAP.

Longhaired Genius

3:49 pm on Aug 20, 2005 (gmt 0)

10+ Year Member



PHP includes Perl-compatible regular-expressions:
[docs.php.net...]

adni18

8:04 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So how would something like this be done in PHP (this is perl syntax)?

$string=~s/(\[.{1,}\])/checkimg($1)/g;

dmorison

8:15 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You'd use preg_replace() [uk.php.net] something like:

$string = preg_replace("/(\[.{1,}\])/g","checkimg($1)",$string);

adni18

8:21 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



thanks!

adni18

8:38 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ah! That replaces the $1, but how do I make it replace it with the return value of a PHP function, with the parameter of $1?

dmorison

8:47 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$string = preg_replace("/(\[.{1,}\])/ge","checkimg($1)",$string);

...the e modifier causes the replacement string to be interpreted as PHP code.

adni18

9:33 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



...also had to add quotes before and after $1...

checkimg(\"$1\")

Thanks!

adni18

9:48 pm on Aug 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Grrr. For some reason the /g modifier isn't working. Any workaround?

coopster

2:04 am on Aug 21, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



preg_replace() [php.net] searches the subject for matches to the pattern and replaces every such reference with the replacement. The /g modifier is not valid here, it is already global.

adni18

9:52 pm on Aug 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



PHP doesn't seem to want to replace all the instances, though. Whenever there is more than one instance, it doesn't do anything.... :(

coopster

11:17 pm on Aug 29, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Can you offer an example of the string you are searching and the pattern you are using?