...

View Full Version : regular expressions



roice
03-03-2010, 08:28 AM
Hello everyone,
My name is Roi and I need your help.
Hope you will be able to help me-
I wrote a script that take variable that contain HTML code,. it replace the exact word "php" (no matter if it is contain capital letters) with the word "asp"
for example, if the variable contain:

<a href='http://www.php.com'>myphp</a> best <b>php</b> website <h1>PhP!!!</h1> php and myphp or phpme - <u>php!</u>!the result will be

<a href='http://www.asp.com'>myphp</a> best <b>asp</b> website <h1>asp!!!</h1> aspand myphp or phpme - <u>asp!</u>! well, the problem is that it althouth replace the letters inside the THML tags and because of that the links changed...
Here is my code:

function keepcase($word, $replace) {
$replace[0] = (ctype_upper($word[0]) ? strtoupper($replace[0]) : $replace[0]);

return $replace;
}

$text = strtolower(file_get_contents($folder.$file));
$replace = "asp";
$word = "php";
$output = preg_replace('/\b' . preg_quote($word) . '\b/ei', "keepcase('\\0', '$replace')", $text);

echo $output; What should I change if I want the replacements to be only on the text between the HTML tags?

Thank you in advance,
Roi.

JAY6390
03-03-2010, 11:50 AM
$result = preg_replace('/(>[^<]*)\b(' . preg_quote($word) . ')\b/sime', "$1.keepcase('$2', '$replace')", $subject);

Something like that will do it

roice
03-03-2010, 01:15 PM
Hi JAY6390,
Thank you for your reply!
here is the code with your changes:


function keepcase($word, $replace) {
$replace[0] = (ctype_upper($word[0]) ? strtoupper($replace[0]) : $replace[0]);

return $replace;
}

$text = file_get_contents($folder.$file);
$replace = "asp";
$word = "php";
$output = preg_replace('/(>[^<]*)\b(' . preg_quote($word) . ')\b/sime', "$1.keepcase('$2', '$replace')", $text);
echo $output;

But I got an error message:


Parse error: syntax error, unexpected '>' in /home/scrambler/scrabler.php(66) : regexp code on line 1

Fatal error: preg_replace() [<a href='function.preg-replace'>function.preg-replace</a>]: Failed evaluating code: &gt;.keepcase('php', 'asp')



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum