note 84285 added to function.preg-replace

From: Date: Mon, 07 Jul 2008 22:22:42 +0000
Subject: note 84285 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-141251@lists.php.net to get a copy of this message
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. ---- Server IP: 212.124.37.9 Probable Submitter: 79.193.94.13 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- https://master.php.net/note/edit/84285 Del: integrated -- https://master.php.net/note/delete/84285/integrated Del: useless -- https://master.php.net/note/delete/84285/useless Del: bad code -- https://master.php.net/note/delete/84285/bad+code Del: spam -- https://master.php.net/note/delete/84285/spam Del: non-english -- https://master.php.net/note/delete/84285/non-english Del: in docs -- https://master.php.net/note/delete/84285/in+docs Del: other reasons-- https://master.php.net/note/delete/84285 Reject -- https://master.php.net/note/reject/84285 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#141251) next »