1
$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

4

3 回答 3

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

于 2012-11-12T12:03:17.880 回答
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);

与 Davo 的答案条一样,将为您提供不区分大小写的搜索

于 2012-11-12T12:05:00.543 回答
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]);
}
于 2012-11-12T12:21:00.863 回答