2013-02-05 116 views
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 

我该怎么办呢?

回答

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); 
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" 
相关问题