$phrases = array(
"New York", "New Jersey", "South Dakota",
"South Carolina", "Computer Repair Tech"
);
$string = "I live in New York, but used to live in New Jersey working as a " .
"computer repair tech.";
提取$phrases
$string
$new_string
输出应为:New York New Jersey Computer Repair Tech
答案 0 :(得分:3)
$new_string = "";
foreach($phrases as $p) {
$pos = stripos($string, $p);
if ($pos !== false) {
$new_string .= " ".$p;
}
}
$new_string = trim($new_string); // to remove additional space at the beginnig
echo $new_string;
请注意,如果您想要区分大小写的搜索,那么您的查找将不区分大小写
使用strpos()
代替stripos
答案 1 :(得分:3)
您需要使用stripos(以获得最佳效率):http://php.net/manual/en/function.stripos.php。您的代码将类似于以下内容:
$matches = array();
foreach($phrases as $phrase) {
if(stripos($string,$phrase) !== false){
$matches[] = $phrase;
}
}
$new_string = implode(" ",$matches);
与达沃的回答条带一样,会给你一个不区分大小写的搜索
答案 2 :(得分:2)
尝试此功能
$phrases = array("New York", "New Jersey", "South Dakota", "South Carolina", "Computer Repair Tech");
$string = ("I live in New York, but used to live in New Jersey working as a computer repair tech.");
$matches = stringSearch($phrases, $string);
var_dump($matches);
function stringSearch($phrases, $string){
$phrases1 = trim(implode('|', $phrases));
$phrases1 = str_replace(' ', '\s', $phrases1);
preg_match_all("/$phrases1/s", $string, $matches);
return implode(' ', $matches[0]);
}