...

View Full Version : Simple regexp (or so I think)



jskaar
06-20-2006, 12:31 PM
But I'm new at this regexp-thing:S

Say I got the following:
$text = "Hi, how are <tag>you <b>my</b> friend?</tag>";

1. How do I get hold of the content of the tag? (That which is between <tag> and </tag>.)

2. And then I would like to replace "<tag>you <b>my</b> friend?</tag>" with "another text".

If someone who can this wonderful, but jet difficult, regexp stuff could help me?

Regards and thanks!

lavinpj1
06-20-2006, 05:46 PM
<?php
$text = "Hi, how are <tag>you <b>my</b> friend?</tag>";
preg_match("@(\<tag\>).*(?=\<\/tag\>)@", $text, $match);
echo substr($match[0], 5); //echos "you <b>my</b> friend?"
$text = str_replace($match[0] . '</tag>', 'another text', $text);
echo $text; //echos "Hi, how are another text"
?>


~Phil~

jskaar
06-21-2006, 09:08 AM
Hi, I messed around a little bit, and came up with something that seems to work:

$text = "Hi, how are <tag>you <b>my</b> friend?</tag>";
$match = array();
preg_match("/<tag>(.*)<\/tag>/i", $text, $match);
echo $match[1];
echo preg_replace("/<tag>(.*)<\/tag>/i", "another text", $text);
Is this doing the same as lavinpj1, or am I missing something important? It echoes the same for the example.

Question:

preg_match("@(\<tag\>).*(?=\<\/tag\>)@", $text, $match);
What does the "@" means, and is is necessary to escape the "<" and ">"?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum