简体   繁体   中英

PHP- How to split a long array (sentence) into smaller array (keywords) to pass through a foreach loop

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 (ie 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 (ie 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.

Try:

function funFun($pst, $lst, $spc){
  $sc = '/\\'.implode('|\\', $spc).'/';
  foreach($pst as $v){
    $pr[] = preg_replace($sc, '', $v);
  }
  $ps = preg_split('/\s+/', $pr);
  foreach($ps as $v){
    $a[] = $lst[$v];
  }
  return $a;
}
$resArray = funFun($post, $list, array(',', '.', '(', ')', '-'));
<?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 ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM