Page 1 of 1

Capture return code from preg_replace()?

Posted: Sat Mar 01, 2003 12:06 pm
by rxsid
Hi all,

Im using preg_replace to successfuly replace anything found in the search array:

Code: Select all

$search = array ("'a'", "'b'", "'c'");
$replace = array ("","","");

$text = preg_replace ($search, $replace, $document);
This works great.
My question is, how to I capture, or test for the successful return of this function? In other words, if something is found and replaced, will $text = 1? or will $text = "True".

I want to be able to get the return code of this function, to be able to display some info after the fact.

Thanks.

Posted: Sat Mar 01, 2003 1:50 pm
by volka
the return value is always the altered string (or the same if nothing has been changed). If you really must know wether something has changed you can compare in- and output, e.g.

Code: Select all

if ($text != $document)
    //something has been changed

Posted: Sat Mar 01, 2003 2:01 pm
by twigletmac
On a side note, if you're not doing regular expression replaces - then using str_replace() will be faster than preg_replace().

Mac

Posted: Sat Mar 01, 2003 7:33 pm
by rxsid
hmm...
seems I often make coding more difficult than it needs to be.

simple answers but exactely what I was looking for.

I'll:
1. change to str_replace
2. compare before and after.

thanks to both twigletmac & volka!