note 94678 added to function.preg-match

From: Date: Tue, 17 Nov 2009 22:47:45 +0000
Subject: note 94678 added to function.preg-match
Groups: php.notes 
Request: Send a blank email to php-notes+get-163015@lists.php.net to get a copy of this message
I spent a while replacing all my ereg() calls to preg_match(), since ereg() is now deprecated and will not be supported as of v 6.0. Just a warning regarding the conversion, the two functions behave very similarly, but not exactly alike. Obviously, you will need to delimit your pattern with '/' or '|' characters. The difference that stumped me was that preg_replace overwrites the $matches array regardless if a match was found. If no match was found, $matches is simply empty. ereg(), however, would leave $matches alone if a match was not found. In my code, I had repeated calls to ereg, and was populating $matches with each match. I was only interested in the last match. However, with preg_match, if the very last call to the function did not result in a match, the $matches array would be overwritten with a blank value. Here is an example code snippet to illustrate: <? $test = array('yes','no','yes','no','yes','no'); foreach ($test as $key=>$value) { ereg("yes",$value,$matches1); preg_match("|yes|",$value,$matches2); } print "ereg result: $matches1[0]<br>"; print "preg_match result: $matches2[0]<br>"; ?> The output is: ereg result: yes preg_match result: ($matches2[0] in this case is empty) I believe the preg_match behavior is cleaner. I just thought I would report this to hopefully save others some time. ---- Server IP: 64.71.164.2 Probable Submitter: 128.120.27.173 ---- Manual Page -- http://www.php.net/manual/en/function.preg-match.php Edit -- https://master.php.net/note/edit/94678 Del: integrated -- https://master.php.net/note/delete/94678/integrated Del: useless -- https://master.php.net/note/delete/94678/useless Del: bad code -- https://master.php.net/note/delete/94678/bad+code Del: spam -- https://master.php.net/note/delete/94678/spam Del: non-english -- https://master.php.net/note/delete/94678/non-english Del: in docs -- https://master.php.net/note/delete/94678/in+docs Del: other reasons-- https://master.php.net/note/delete/94678 Reject -- https://master.php.net/note/reject/94678 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#163015) next »