note 97904 added to function.str-replace
| From: | christian dot reinecke at web dot de | Date: | Fri, 14 May 2010 19:06:28 +0000 |
| Subject: | note 97904 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-169266@lists.php.net to get a copy of this message | ||
If you need to replace a string in another, but only once but still in all possible combinations
(f.e. to replace "a" with "x" in "aba" to get array("xba",
"abx")) you can use this function:
<?php
function getSingleReplaceCombinations($replace, $with, $inHaystack)
{
$splits = explode($replace, $inHaystack);
$result = array();
for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {
$previous = array_slice($splits, 0, $i);
$next = array_slice($splits, $i);
$combine = array_pop($previous) . $with . array_shift($next);
$result[] = implode($replace, array_merge($previous, array($combine), $next));
}
return $result;
}
var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as
mentioned above
?>
It may not be the best in performance, but it works.
----
Server IP: 85.214.154.209
Probable Submitter: 78.42.25.223
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/97904
Del: integrated -- https://master.php.net/note/delete/97904/integrated
Del: useless -- https://master.php.net/note/delete/97904/useless
Del: bad code -- https://master.php.net/note/delete/97904/bad+code
Del: spam -- https://master.php.net/note/delete/97904/spam
Del: non-english -- https://master.php.net/note/delete/97904/non-english
Del: in docs -- https://master.php.net/note/delete/97904/in+docs
Del: other reasons-- https://master.php.net/note/delete/97904
Reject -- https://master.php.net/note/reject/97904
Search -- https://master.php.net/manage/user-notes.php