note 79929 deleted from function.preg-replace by felipe
| From: | felipe@php.net | Date: | Sun, 23 Mar 2008 22:59:33 +0000 |
| Subject: | note 79929 deleted from function.preg-replace by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137397@lists.php.net to get a copy of this message | ||
Note Submitter: fc no-spam-remove modz at yahoo dot com
----
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
?>