note 79929 added to function.preg-replace

From: Date: Thu, 20 Dec 2007 00:33:38 +0000
Subject: note 79929 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-133799@lists.php.net to get a copy of this message
For those of you wondering if preg_replace() can replace substrings from the regex pattern, it cannot. It can only replace the full pattern match. Here's a function I made to replace the actual substrings within the haystack: <?php function preg_replace_subs($pat,$hay,$replaceArr, $out = false) { # ie for replaceArr: array(2 => 'two', 4 => 'four') //$out must have 1 flag set which is offset capture if (empty($replaceArr)) { die('<br><b>Error:</b><br>Replace Array argument cannot be empty'); } $matches = true; if (!$out) { $matches = preg_match_all($pat, $hay, $out, PREG_OFFSET_CAPTURE); } if ($matches && !empty($out[0])) { $hayChars = str_split($hay); unset($out[0]); foreach ($out as $subKey => $subArr) { //each sub $1 -... if (isset($replaceArr[$subKey])) { foreach ($subArr as $subInfo) { //each match of this sub $sub = $subInfo[0]; $subOff = $subInfo[1]; $subLen = strlen($sub); //echo "replacing $sub<br>at offset: $subOff<br>it is $subLen long<br>"; if (isset($hayChars[$subOff])) { if ($subLen > 1) { //del rest of positions where old sub existed for ($x = $subOff+1; $x<=(($subOff+$subLen)-1); $x++) { unset($hayChars[$x]); } } //replace substring $hayChars[$subOff] = $replaceArr[$subKey]; } else { //o($hayChars,100,100); die('<br><b>Error:</b><br>Cannot replace '.htmlentities($sub).' because it exists in another substring which has already been replaced.'); } } } } return implode('',$hayChars); } else { return false; } } $pat = '~(hello (<b>)) it is a (wonderful)</b> day<c> (ou(tsi)de) (so lovely)~'; $hay = 'hello <b> it is a wonderful</b> day<c> outside so lovely hello <b> it is a wonderful</b> day<c> outside so lovely'; $rArr[2] = 'two'; $rArr[4] = 'four'; echo htmlentities(preg_replace_subs($pat,$hay,$rArr)); //outputs: hello two it is a wonderful</b> day<c> four so lovely hello two it is a wonderful</b> day<c> four so lovely ?> ---- Server IP: 64.71.164.2 Probable Submitter: 68.53.235.219 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- https://master.php.net/note/edit/79929 Del: integrated -- https://master.php.net/note/delete/79929/integrated Del: useless -- https://master.php.net/note/delete/79929/useless Del: bad code -- https://master.php.net/note/delete/79929/bad+code Del: spam -- https://master.php.net/note/delete/79929/spam Del: non-english -- https://master.php.net/note/delete/79929/non-english Del: in docs -- https://master.php.net/note/delete/79929/in+docs Del: other reasons-- https://master.php.net/note/delete/79929 Reject -- https://master.php.net/note/reject/79929 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#133799) next »