[英]PHP- How to split a long array (sentence) into smaller array (keywords) to pass through a foreach loop
我使用如下代碼:
$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;
}
}
}
該代碼可以很好地傳遞$post = array ('Humans', 'Tony Montana', 'Tech', 'Creative');
等$post = array ('Humans', 'Tony Montana', 'Tech', 'Creative');
使關鍵字與另一個數組中的另一個關鍵字列表匹配。 但是我想傳遞一個帶有$post
類的結構的數組(在代碼中),以從帖子標題中找到關鍵字。 因此,我的問題是我該如何將$post
值(即This is a test - That game is awesome (Cristiano Ronaldo is a great Soccer Player).
)分割成長度小於2個字符的小字(即This
, test
, That
, game
, awesome
, Cristiano
, Ronaldo
, great
, Soccer
和Player
),將通過之前去除特殊字符$post
進入foreach循環。 非常感謝您在這個問題上的幫助。
嘗試:
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);
現場演示: 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 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.