我想扫描一段并用另一个词替换其中的针。例如
$needles = array('head', 'limbs', 'trunk');
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";
需要最终输出
Main part of human body is this, this and this
我该怎么做?
我想扫描一段并用另一个词替换其中的针。例如
$needles = array('head', 'limbs', 'trunk');
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";
需要最终输出
Main part of human body is this, this and this
我该怎么做?
假设您使用的是 PHP,您可以尝试str_ireplace
.
$needles = array('head', 'limbs', 'trunk');
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";
echo str_ireplace($needles, $to_replace, $haystack); // prints "Main parts of human body is this, this and this"
使用 preg_replace :
$needles = array('head', 'limbs', 'trunk');
$pattern = '/' . implode('|', $needles) . '/i';
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";
echo preg_replace($pattern, $to_replace, $haystack);