December 29th, 1999, 02:41 AM
Here's some regular expression fun for everyone:
I have an associative array like so:
$dogs["spaniel"] = "buffy";
$dogs["beagel"] = "floppy";
$dogs["terrier"] = "chewy";
and then I have a marked up string like so:
"<spaniel> + <beagel> + <terrier>"
What I want to do is programatically replace the tags with the
corresponding names from the associative array. Essentially I
should end up with :
"buffy + floppy + chewy"
This is what I was hoping I was going to be able to do:
$newstring = eregi_replace ( "<(.*)>", $dogs["1"], $oldstring );
but it doesn't seem to work. Does anyone have a better solution
(one that actually works!). Many thanks to those that respond!
Hint: my solution fails for two reasons I think. 1) my regular expression
isn't matching right. The (.*) of the regular expression seems to consume
the '>' and keeps going all the way to the end of the string. Second, I don't
think the "1" is going to work inside the array (although this might just
be a side effect of the first problem).
Please respond via email because I don't frequent the newsgroups as often
as I'd like to.
December 30th, 1999, 12:22 AM
Well, usually you would use (.*)? or (.*?) to restrict the matching of (.*), but that doesn't work as expected in php3's ereg_replace() function. So you could also use [^(<|> )]* but that doesn't work because then backtracking won't work. So we are left with preg_replace(). /<(.*?)>/ would then work, however to use PHP variables in the replacement code, you would have to use the /e modifier described at http://www.php.net/manual/function.preg-replace.php3 which is only available in PHP 4.0 so if you are using or can upgrade to PHP 4.0, this would be working code:
$newstring = preg_replace("/<(.*?)>/e", "echo($dogs)", $oldstring);
(you might have to use something funky like eval() in there, haven't tested the /e part because I'm not upgrading to PHP 4.0 until it's out of beta)
If anyone else can find a solution for php3, I'd love to see it.
(posted and emailed)
January 4th, 2000, 03:09 PM
January 5th, 2000, 03:04 PM
If that's all you need to do, its pretty easy, but it gets more complicated if there is something after the URL. In this case, you would have to change the pattern to exclude certain characters from the pattern (spaces for example). It would be pretty easy in perl, but PHP's regular expressions are screwy. I'll try to post up a better solution when I get more time (if someone doesn't beat me to it).
$pattern = "(http://.*)";
$replace = "<A HREF='1'>1</A>";
$html = "Go to <A HREF="http://www.php.net";" TARGET=_blank>http://www.php.net";</A>
print eregi_replace ( $pattern, $replace , $html );