dotxxh0998 2014-06-11 00:53
浏览 43
已采纳

PHP-如何将长数组(句子)拆分为较小的数组(关键字)以通过foreach循环

I use a piece of code as follows:

$list = array(
"This" => "9",
"great" => "10",
"God Father" => "11",
"Tony Montana" => "12",
"Ronaldo" => "13",
"Al Pacino" => "14",
"Humans" => "15",
"Play" => "16"
);

$post = Array ( [title] => "This is a test - That game is awesome (Cristiano Ronaldo is a great Soccer Player).",
                           "This is a not a test - That game is OK (Maradonal was a great Soccer Player)."
                                );

foreach ($post as $keyword) {
    foreach ($list as $word=>$num) {
        $sim_chars = similar_text($keyword, $word);
        if ($sim_chars/strlen($keyword) > .8 || $sim_chars/strlen($word) > .8) {
            $all_key_values[] = $num;
            $all_keys[] = $word;
        }
        elseif (stripos($keyword, $word) !== false || strpos($word, $keyword) !== false) {
            $sll_key_values[] = $num;
            $all_keys[] = $word;
        }
    }        
}

The code works well to pass an array like $post = array ('Humans', 'Tony Montana', 'Tech', 'Creative'); to match the keywords with another list of keywords in a different array. But I want to pass an array with $post like structure (in the code) to find the keywords from the post titles. So, my question is how can I split the $post value (i.e. This is a test - That game is awesome (Cristiano Ronaldo is a great Soccer Player).) into smaller words which are greater than 2 characters in length (i.e. This, test, That, game, awesome, Cristiano, Ronaldo, great, Soccer and Player) and removing the special characters before passing the $post into the foreach loops. Thanks a lot for helping me on this problem.

  • 写回答

2条回答 默认 最新

  • douna3367 2014-06-11 01:26
    关注
    <?php
    
    $str="This is a test - That game is awesome (Cristiano Ronaldo is a great Soccer Player)";
    
    //clean string:
    
    $str=preg_replace("/[^A-Za-z0-9 ]/", '', $str); 
    
        //first explode it
        $e=explode(' ',$str);
    
    //loop to remove short words
        $out=array();
        foreach ($e as $a){
    
            if(strlen($a)>2){
            $out[]=$a;  
            }
        }
    
    print_r($out);
    

    Live Demo: http://codepad.viper-7.com/CEvYdx

    Array ( [0] => This [1] => test [2] => That [3] => game [4] => awesome [5] => Cristiano [6] => Ronaldo [7] => great [8] => Soccer [9] => Player ) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装