note 84063 deleted from function.preg-replace by mgf

From: Date: Wed, 02 Jul 2008 10:00:43 +0000
Subject: note 84063 deleted from function.preg-replace by mgf
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-141059@lists.php.net to get a copy of this message
Note Submitter: Santosh Patnaik ---- Neither preg_replace nor preg_replace_callback work as expected with alternatives when the pattern is a string with the alternatives specified using the '|' meta-character. Having the pattern as an array of the alternatives seems to be the only work-around. <?php // Want a1ab2bc3cD4Da5ab6b $t = 'A1AB2BC3CD4DA5AB6B'; // Using the e modifier; get a1aD4Da5a echo preg_replace('((A)(.+?)(A))|((B)(.+?)(B))|((C)(.+?)(C))e', 'strtolower("$2"). "$3". strtolower("$4")', $t); // Using a callback; get a1aD4Da5a echo preg_replace_callback('((A)(.+?)(A))|((B)(.+?)(B))|((C)(.+?)(C))', 'f', $t); function f($m){ return strtolower($m[2]). $m[3]. strtolower($m[4]); } // Using pattern array; get a1ab2bc3cD4Da5ab6b $r = array('(A)(.+?)(A)e', '(B)(.+?)(B)e', '(C)(.+?)(C)e'); echo preg_replace($r, 'strtolower("$1"). "$2". strtolower("$3")', $t); ?>

« previous php.notes (#141059) next »