I have thrown together a little function to find and replace a string within a block of text but it seems to be draining resources. I figure this is because I am trying to run it on a whole HTML page.
All I really want to do is replace all text except the title tag.
Here is my function:
/**
* Find and replace strings with skip
*
* @param string $haystack
* @param string $needle
* @param int $start
* @param int $skip
*
* @return mixed
*/
function skip_and_replace($haystack, $needle, $start = 0, $skip = 0) {
$count = 0;
while ($pos = strpos(($haystack), $needle, $start) !== false) {
if ($count <= $skip)
continue;
substr_replace($haystack, ' M<sup>c</sup>', $pos, strlen($needle));
$start = $pos+1;
$count++;
}
return $haystack;
}
Can anyone please help with making this function easier on the memory or let me know if there is a better way to achieve my end goal?
If you want to replace all but the first instance of a string, this should work. Can't guarantee it will scale well, but it's the first thing that came to mind.
$haystack = "foo bar baz foo bar baz foo bar baz";
$oldtext = "bar";
$newtext = "rab";
$arr = explode($oldtext, $haystack, 2);
$arr[1] = str_replace($oldtext, $newtext, $arr[1]);
$new_string = implode($oldtext, $arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.