str_replace 除了第一个
str_replace all but first
我拼凑了一个小函数来查找和替换文本块中的字符串,但它似乎正在耗尽资源。我想这是因为我正试图 运行 它在整个 HTML 页面上。
我真正想做的就是替换除标题标签之外的所有文本。
这是我的函数:
/**
* 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;
}
任何人都可以帮助使这个功能更容易记忆,或者让我知道是否有更好的方法来实现我的最终目标?
如果您想替换字符串的第一个实例以外的所有实例,这应该可行。不能保证它会很好地扩展,但这是第一个想到的。
$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);
我拼凑了一个小函数来查找和替换文本块中的字符串,但它似乎正在耗尽资源。我想这是因为我正试图 运行 它在整个 HTML 页面上。
我真正想做的就是替换除标题标签之外的所有文本。
这是我的函数:
/**
* 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;
}
任何人都可以帮助使这个功能更容易记忆,或者让我知道是否有更好的方法来实现我的最终目标?
如果您想替换字符串的第一个实例以外的所有实例,这应该可行。不能保证它会很好地扩展,但这是第一个想到的。
$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);