I want to scan a paragraph and replace needles in that with another word. for example
我想扫描一个段落并用另一个词替换那个针。例如
$needles = array('head', 'limbs', 'trunk');
$to_replace = "this";
$haystack = "Main parts of human body is head, Limbs and Trunk";
Final out put needed
最终输出需要
Main part of human body is this, this and this
How can I do it?
我该怎么做?
2 个解决方案
#1
1
With preg_replace :
使用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);
#2
1
Assuming you are using PHP, you can try str_ireplace
.
假设您使用的是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
With preg_replace :
使用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);
#2
1
Assuming you are using PHP, you can try str_ireplace
.
假设您使用的是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"