根据数组列表从字符串中选择单词

时间:2012-05-18 11:07:10

标签: php

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

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

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

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

请有人帮我这个。 THX

5 个答案:

答案 0 :(得分:1)

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

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

使用风险自负:)

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

答案 1 :(得分: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
        )

)

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

答案 2 :(得分: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;

答案 3 :(得分:0)

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

<?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.' ';    
}
?>

答案 4 :(得分:0)

$narray=array();

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

echo @implode(" ",$narray);