2013-02-05 113 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" 
相關問題