所有匹配项 – 永夜 https://www.shuijingwanwq.com 没有不值得去解决的问题,也没有不值得去学习的技术! Sun, 29 Jan 2023 05:55:42 +0000 zh-Hans hourly 1 https://wordpress.org/?v=7.0 在 Lavavel 6 中替换字符串中给定值的所有匹配项 https://www.shuijingwanwq.com/2023/01/29/7376/ https://www.shuijingwanwq.com/2023/01/29/7376/#respond Sun, 29 Jan 2023 05:55:42 +0000 https://www.shuijingwanwq.com/?p=7376 浏览量: 53 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
由于数组 $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
字符串中的 default 全部被替换为 Basic

图2



string(49) "The event will take place between Basic and Basic"


]]>
https://www.shuijingwanwq.com/2023/01/29/7376/feed/ 0