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"
$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); PHP:
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 Code (markup): $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 Code (markup):
<?php $str = "xyz xyz xyz www.xyz.com xyz XyZ xyz"; $str = preg_replace('/(^|\s)xyz($|\s)/i', '$1yyy$2', $str); echo $str; ?> Code (php): I do think should do what you want. If not, could you expand? :-/
$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; Code (markup):