note 84063 added to function.preg-replace
| From: | SantoshPatnaik at osu1 dot php dot net | Date: | Thu, 26 Jun 2008 03:32:12 +0000 |
| Subject: | note 84063 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-140825@lists.php.net to get a copy of this message | ||
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);
?>
----
Server IP: 69.147.83.197
Probable Submitter: 67.99.175.226
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- https://master.php.net/note/edit/84063
Del: integrated -- https://master.php.net/note/delete/84063/integrated
Del: useless -- https://master.php.net/note/delete/84063/useless
Del: bad code -- https://master.php.net/note/delete/84063/bad+code
Del: spam -- https://master.php.net/note/delete/84063/spam
Del: non-english -- https://master.php.net/note/delete/84063/non-english
Del: in docs -- https://master.php.net/note/delete/84063/in+docs
Del: other reasons-- https://master.php.net/note/delete/84063
Reject -- https://master.php.net/note/reject/84063
Search -- https://master.php.net/manage/user-notes.php