Page 1 of 1

Replace using arrays...

Posted: Sat Jan 22, 2005 11:15 pm
by danoise
OK I admit that I am new to PHP, and that the amount of commands that can manipulate arrays are overwhelming to say the least...But I'm having trouble doing something, which is not really covered by the PHP documentation (I think):

Performing regular expression matches in string of text (HTML), where each match is replaced by the value of an array.

In code it would read something like (I did not test the code, it's just there for illustration purposes ;-)

Code: Select all

$my_arr=array('text1','text2,'text3');
$html_string="blablablablabla_blah_bla_blah_blabla_blah_";
//match against "_blah_" not "bla"
$reg_exp="/_blah_/";
Now here's the problem. What function is most useful when I want to replace matches *one at a time* so the resulting string would read:

blablablablablatext1blatext2blablatext3 <- results from array

instead of

blablablablablatext1blatext1blablatext1 <- the first match all the way

I've read about preg_replace_callback, but I can't get the array fed into the callback. Which is the solution I guess...

Is there a way, not to complicated,... :-)

Posted: Sat Jan 22, 2005 11:20 pm
by feyd
read about the 'e' modifier for preg_replace

Posted: Sat Jan 22, 2005 11:28 pm
by mrmachoman
Maybe this link will help.

http://www.phpfreaks.com/tutorials/122/0.php

Its a language filter sounds like might be able to be adapted to your needs.

Posted: Sun Jan 23, 2005 10:03 am
by danoise
feyd, that "e" seems promising. I've been experimenting a bit, but I still can't seem to make it work...The thing is, I need to increment my array each time a match is made. So preg_replace() would need something like

Code: Select all

preg_replace($reg_exp, "$my_array&#1111;$count++]", $string);
If the return values are incapsulated in strings it doesn't produce any errors, but then the code isn't evaluted, just printed...

As for the "language filter" link... What I would need was a language filter that matched "****" and replaced it with curses from a list !!! Hehe...quite the opposite... :o

Posted: Sun Jan 23, 2005 10:06 am
by feyd
try that execute string with single quotes ;)

you're asking php to parse those variables before calling the function.

Posted: Sun Jan 23, 2005 10:19 am
by danoise
feyd wrote:try that execute string with single quotes ;)
You the man feyd...it works!!

And thanks for all the help - I think I'll become a regular on this forum :-)