使用数组搜索并替换字符串中的单词

时间:2013-02-05 15:25:25

标签: arrays preg-replace preg-match-all

我想扫描一个段落并用另一个词替换那个针。例如

$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

我该怎么做?

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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);