note 84285 deleted from function.preg-replace by crell
| From: | crell@php.net | Date: | Fri, 01 Jul 2022 19:55:33 +0000 |
| Subject: | note 84285 deleted from function.preg-replace by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218875@lists.php.net to get a copy of this message | ||
Note Submitter: akniep at rayo dot info
----
preg_replace (and other preg-functions) return null instead of a string when encountering problems
you probably did not think about!
-------------------------
It may not be obvious to everybody that the function returns NULL if an error of any kind occurres.
An error I happen to stumple about quite often was the back-tracking-limit:
http://de.php.net/manual/de/pcre.configuration.php
#ini.pcre.backtrack-limit
When working with HTML-documents and their parsing it happens that you encounter documents that have
a length of over 100.000 characters and that may lead to certain regular-expressions to fail due the
back-tracking-limit of above.
A regular-expression that is ungreedy ("U", http://de.php.net/manual/de/reference.pcre.pattern.modifiers.php)
often does the job, but still: sometimes you just need a greedy regular expression working on long
strings ...
Since, an unhandled return-value of NULL usually creates a consecutive error in the application with
unwanted and unforeseen consequences, I found the following solution to be quite helpful and at
least save the application from crashing:
<?php
$string_after = preg_replace( '/some_regexp/', "replacement", $string_before );
// if some error occurred we go on working with the unchanged original string
if (PREG_NO_ERROR !== preg_last_error())
{
$string_after = $string_before;
// put email-sending or a log-message here
} //if
// free memory
unset( $string_before );
?>
You may or should also put a log-message or the sending of an email into the if-condition in order
to get informed, once, one of your regular-expressions does not have the effect you desired it to
have.