0

我想扫描一段并用另一个词替换其中的针。例如

$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

我该怎么做?

4

2 回答 2

1

假设您使用的是 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"
于 2013-02-05T15:35:47.013 回答
1

使用 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);
于 2013-02-05T15:57:18.267 回答