我需要一个str_replace或任何在第一个元素之后起作用的东西:
"Hello-World-I-am-Pr-Pro"
这就是我想要的结果:
"Hello-World I am Pr Pro"
PHP正则表达式引擎将使用preg_replace为您执行此操作:
function replaceViaRegex($needle, $to, $haystack)
{
$regexStr = '/'.preg_quote($needle, '/').'/';
$result = preg_replace($regexStr, $to, $haystack, 1);
return $result;
}
$foo = "Hello-World-I-am-Pr-Pro";
$foo2 = replaceViaRegex('-', ' ', $foo);
echo $foo2;
或者,你可以这样做
$foo = "Hello-World-I-am-Pr-Pro";
$regex = '/-/';
$foo2 = preg_replace($regex, ' ', $foo, 1);
......但那灵活性要差得多。甚至
$foo2 = preg_replace('/-/', ' ', "Hello-World-I-am-Pr-Pro", 1);
...但是我在过去使用变量进行preg_replace工作时遇到了麻烦,所以我只是避免让它变得那么密集。
我使上面的功能非常清晰和简单,以便您可以按照您的选择遵循逻辑并进行修改。如果你想要好的,可维护的代码,那么使用第一个版本比使用其他两个版本要好得多。