在 Lavavel 6 中替换字符串中给定值的所有匹配项
1、现在有一个字符串,其内容如下
The event will take place between default and default
2、期望将字符串中的 default 批量替换为 Basic
3、参考 Str::replaceArray 函数使用数组顺序替换字符串中的给定值
$string = 'The event will take place between default and default'; $replaced = Str::replaceArray('default', ['Basic'], $string); var_dump($replaced); exit;
4、由于数组 $replace 中仅包含一个元素,最终仅替换了一个 default。如图1
string(51) "The event will take place between Basic and default"
5、参考 Str::replaceArray 函数,修改为如下实现
$string = 'The event will take place between default and default'; $search = 'default'; $replace = 'Basic'; $segments = explode($search, $string); $result = array_shift($segments); foreach ($segments as $segment) { $result .= $replace . $segment; } var_dump($result); exit;
6、字符串中的 default 全部被替换为 Basic。如图2
string(49) "The event will take place between Basic and Basic"
近期评论