Jump to content


Photo

[SOLVED] Regex backreference: use as array index?


  • Please log in to reply
3 replies to this topic

#1 tox_yray

tox_yray
  • Members
  • Pip
  • Newbie
  • 7 posts

Posted 28 August 2006 - 09:49 PM

Ok, here is the problem:

I have this little bit of code:

<?php

$lole = array('rouge', 'vert', 'bleu');

$STRING = "Le ciel est $$!!WIDTH2++--";

echo preg_replace("/\\$\\$!!WIDTH(\\d+)\\+\\+--/", "\\1", $STRING);

?>

The Regex is proper as the script echoes "Le ciel est 2". However, I would like him to echo "Le ciel est bleu" (where "bleu" is the index 2 of array $lole... You get the picture...)

I tried many different solutions but none seem to work. Here is what I've tried:
echo preg_replace("/\\$\\$!!WIDTH(\\d+)\\+\\+--/", $lole["\\1"], $STRING);
echo preg_replace("/\\$\\$!!WIDTH(\\d+)\\+\\+--/", "$lole[\\1]", $STRING);
echo preg_replace("/\\$\\$!!WIDTH(\\d+)\\+\\+--/", $lole[\\1], $STRING);

Thanks for any help you can provide,
Bruno M-A.

#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 28 August 2006 - 11:41 PM

echo preg_replace('/\$\$!!WIDTH(\d+)\+\+--/e', "\$lole[$1]", $STRING);

Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#3 tox_yray

tox_yray
  • Members
  • Pip
  • Newbie
  • 7 posts

Posted 29 August 2006 - 02:43 PM

Works like a charm!!! Thanks a bunch!

#4 GameMusic

GameMusic
  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 03 September 2006 - 06:53 AM

Try preg_replace_callback too.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users