1

我想根据我的数组列表从一个句子中选择特定的单词

$sentence = "please take this words only to display in my browser";

$list = array ("display","browser","words","in");

我希望输出就像“浏览器中显示的单词”

请有人帮我解决这个问题。谢谢

4

5 回答 5

1

我想知道这一个班轮是否会这样做:

echo join(" ", array_intersect($list, explode(" ",$sentence)));

使用风险自负:)

编辑:是的,它完成了工作,刚刚测试过

于 2012-05-18T11:16:10.193 回答
1

你可以用 preg_match 做到这一点:

$sentence = "please take this words only to display in my browser";

$list = array ("display","browser","words","in");

preg_match_all('/\b'.implode('\b|\b', $list).'\b/i', $sentence, $matches) ;
print_r($matches);

你会按顺序得到单词

Array
(
    [0] => Array
        (
            [0] => words
            [1] => display
            [2] => in
            [3] => browser
        )

)

但是,如果文本不是那么简单,请注意正则表达式的性能。

于 2012-05-18T11:21:25.180 回答
0

我不知道任何简短的版本,而不是逐字检查。

$words = explode(" ", $sentence);
$new_sentence_array = array();
foreach($words as $word) {
    if(in_array($word, $list)) {
        $new_sentence_array[] = $word;
    }
}

$new_sentece = implode(" ", $new_sentence_array);
echo $new_sentence;
于 2012-05-18T11:15:56.030 回答
0

strpos我认为您可以在字符串中搜索数组中的每个值,并将其分配给以该值作为键的新数组;这将为您提供一个可排序的数组,然后您可以按照术语在字符串中出现的顺序输出该数组。请参见下文或示例

<?php
$sentence = "please take this words only to display in my browser";

$list = array ("display","browser","words","in");

$found = array();

foreach($list as $k => $v){
    $position = strpos(strtolower($sentence), strtolower($v));
    if($position){
    $found[$position] = $v; 
    }
}

ksort($found);
foreach($found as $v){
    echo $v.' ';    
}
?>
于 2012-05-18T11:27:15.393 回答
0
$narray=array();

foreach ($list as $value) {
    $status=stristr($sentence, $value);
    if ($status) {
        $narray[]=$value;
        }
}

echo @implode(" ",$narray);
于 2012-05-18T11:40:21.113 回答