php - PHP将字符串值从特定位置替换为字符串中的第一个特殊字符
问题描述
如何替换指定字符串中匹配部分的字符串值。
例如,
$haystack = "2548: First Result|2547: Second Result|2550: Third Result|2551: Fourth Result
现在我想从2547 开始更改:到第一个| (管道)在起始值之后。
$result = "2548: First Result|2547: My New String|2550: Third Result|2551: Fourth Result
如何从$haystack变量中替换特定字符串的值。
想要用第一个匹配字符串替换值到 PHP 中的第一个管道字符。
在给定的字符串中,2547:第二个结果| 替换为2547:我的新值| 和字符串的其余部分原样。
是否可以在 PHP 中不使用正则表达式而只使用strpos()或任何其他 php 字符串函数之类的常用函数,或者我们可以使用preg_replace()轻松完成。
解决方案
你可以这样使用
$new_value = "My New String";
$array = explode("|",$haystack);
$new_array = array();
foreach($array as $key)
$new_array[] = (strstr($key,'2547:'))?"2547: ".$new_value:$key;
print_r(implode("|",$new_array));
/*
Output
2548: First Result|2547: My New String|2550: Third Result|2551: Fourth Result
*/