Property in Germany - Find jobs - Loan - Wordpress Themes - Debt Consolidation

PDA

View Full Version : preg_replace pattern help


freerollers
Aug 25th 2008, 7:04 am
can anyone help me how i should write the pattern

i want to replace "xyz" with "yyy" but only if xyz stands alone. Also it should be case-insensitive.

"xyz what go www.xyz.com XyZ test"
->
"yyy what go www.xyz.com yyy test"

grandpa
Aug 25th 2008, 7:19 am
$str = "xyz what go www.xyz.com XyZ test";
$str = eregi_replace('xyz ', 'yyy ', $str);
$str = eregi_replace(' xyz', ' yyy', $str);
echo $str;

freerollers
Aug 25th 2008, 7:22 am
that was kinda smart but does that work if theres a line with "xyz" alone?

nico_swd
Aug 25th 2008, 7:35 am
$str = "xyz what go www.xyz.com XyZ test";
$str = eregi_replace('xyz ', 'yyy ', $str);
$str = eregi_replace(' xyz', ' yyy', $str);
echo $str;

The eregi_* functions are old, ugly, slow, and deprecated (they will be removed in PHP 6). Get used to the preg_* functions. And besides that, they're meant for regular expressions, which you're not using. For simple replacements like yours, use str_replace() and str_ireplace().

Or do it this way:

$text = preg_replace('~(^|\s)xyz($|\s)~si', '$1yyy$2', $text);

grandpa
Aug 25th 2008, 7:52 am
great solution, but failed on this:
$str = "xyz xyz xyz www.xyz.com xyz XyZ xyz";
$str = preg_replace('~(^|\s)xyz($|\s)~si', '$1yyy$2', $str);
echo $str;
//output -> yyy xyz yyy www.xyz.com yyy XyZ yyy


$str = "xyz xyz xyz www.xyz.com xyz XyZ xyz";
$str = preg_replace('~(^|\s)xyz($|\s)~si', '$1yyy$2', $str);
$str = preg_replace('~(^|\s)xyz($|\s)~si', '$1yyy$2', $str);
echo $str;
//output -> yyy yyy yyy www.xyz.com yyy yyy yyy

freerollers
Aug 25th 2008, 8:57 am
thx guys :P but writing the same line doesn't look like the perfect solution? must be better way

Wrighty
Aug 25th 2008, 9:08 am
<?php
$str = "xyz xyz xyz www.xyz.com xyz XyZ xyz";
$str = preg_replace('/(^|\s)xyz($|\s)/i', '$1yyy$2', $str);
echo $str;
?>

I do think should do what you want. If not, could you expand? :-/

grandpa
Aug 25th 2008, 10:25 am
thx guys :P but writing the same line doesn't look like the perfect solution? must be better way

$str = "xyz xyz xyz www.xyz.com xyz XyZ xyz";
$str = preg_replace(array('/(^|\s)xyz($|\s)/i', '/(^|\s)xyz($|\s)/i'), '$1yyy$2', $str);
echo $str;