"9", "great" => "10", "God Father" => "11", "Tony Montana" => "1-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:41:27 24 4
gpt4 key购买 nike

我使用一段代码如下:

$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 结构的数组(在代码中)以从帖子标题中查找关键字。所以,我的问题是如何将 $post 值(即 This is a test - That game is awesome (Cristiano Ronaldo is a great Soccer Player). )拆分为长度大于 2 个字符的较小单词(即 ThistestThatgameawesomeCristianoRonaldogreatSoccerPlayer 、在将 $post 传递到 foreach 循环之前删除特殊字符。非常感谢你帮助我解决这个问题。

最佳答案

<?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 ) 

关于PHP-如何将长数组(句子)拆分为较小的数组(关键字)以通过 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24153090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com