Capture return code from preg_replace()?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rxsid
Forum Commoner
Posts: 82
Joined: Thu Aug 29, 2002 12:04 am

Capture return code from preg_replace()?

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
rxsid
Forum Commoner
Posts: 82
Joined: Thu Aug 29, 2002 12:04 am

Post 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!
Post Reply