468,315 Members | 1,414 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,315 developers. It's quick & easy.

Rexed replace with a list- Can I do this in PHP?

$ar=array("a","b","c");
$string="The third letter of the alpabet is %%2%% and the second is
%%1%%."
$string = preg_replace('/[%]{2}(.*?)[%]{2}/', '$ar[$1]', $string);
echo $string;

I want to see: "The third letter of the alphabet is c and the second
is b."
But what I see instead is: "The third letter of the alphabet is
$ar[$1] and the second is $ar[$1]." I tried double quotes, I tried no
quotes.

The php.net page for preg_replace has some examples in the feedback
that SAY to to this, but go try running them yourself and changing the
numbers- all they really doing is printing the first element, every
time. (In the above example they'd be the equivalent of:
$string = preg_replace('/[%]{2}(.*?)[%]{2}/', $ar[0], $string);)

In perl I could do this easy:
$string=~s/[%]{2}(.*?)[%]{2}/$ar{$1}/g;

How would I do this in PHP?
Jul 17 '05 #1
2 1496
mrbog wrote:
$ar=array("a","b","c");
$string="The third letter of the alpabet is %%2%% and the second is
%%1%%."
$string = preg_replace('/[%]{2}(.*?)[%]{2}/', '$ar[$1]', $string);
echo $string;

I want to see: "The third letter of the alphabet is c and the second
is b." How would I do this in PHP?


Use the /e modifier to evaluate the replaced part

$string = preg_replace('/[%]{2}(.*?)[%]{2}/e', '$ar[$1]', $string);
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #2
Thanks much Pedro.
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by nnes | last post: by
3 posts views Thread by Rodrigo Benenson | last post: by
2 posts views Thread by s | last post: by
3 posts views Thread by Dirk Hagemann | last post: by
4 posts views Thread by jgabbai | last post: by
7 posts views Thread by SpreadTooThin | last post: by
2 posts views Thread by antar2 | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by Teichintx | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.