字符串比较和阵列
问题描述:
试图为用户创建一个搜索在那里我有一个这样的数组切换顺序:字符串比较和阵列
原始数组:
array(2) {
[1]=>
array(1) {
["string"]=>"One two three, Blue, Green, Yellow"
}
[2]=>
array(1) {
["string"]=>"One two four, Blue, Green, Yellow"
}
}
现在我该怎么办正则表达式与从输入字段的话,其可以是“一个两个蓝色四”,然后改变给定的阵列顺序(在这种情况下):
array(2) {
[1]=>
array(1) {
["string"]=>"One two four, Blue, Green, Yellow"
}
[2]=>
array(1) {
["string"]=>"One two three, Blue, Green, Yellow"
}
}
原因原始数组[2]获得了更多匹配。另外我想命令已经改变,如果用户写入“一个两个蓝色的f”
我试过用array_diff但我需要一些相反的array_diff函数(显示所有匹配),并可能是一个正则表达式,使其工作与单个字母。
任何意见将不胜感激!
答
我会爆炸检索词并检查每个单词与stripos()
或substr_count()
针对数组中的字符串。如果它发生的次数减少,那么发生次数越多的次数越多。您可以使用usort()
。
你选机可能看起来像这样的:
class OccurrenceSorter {
private $searchTerm;
public function sort(array $arr, $searchTermStr) {
$this->searchTerm = preg_split('/\s+/', $searchTermStr);
usort($arr, array($this, 'doSort'));
return $arr;
}
private function doSort($a, $b) {
$aScore = $this->getScore($a['string']);
$bScore = $this->getScore($b['string']);
if($aScore == $bScore)
return 0;
return ($aScore < $bScore)?1:-1;
}
private function getScore($str) {
$score = 0;
$strLower = strtolower($str);
foreach($this->searchTerm as $st) {
// substr_count() or strpos() depending on the wished behavior
$score += substr_count($strLower, strtolower($st));
}
return $score;
}
}
$arr = array(
array('string' => 'One two three, Blue, Green, Yellow'),
array('string' => 'One two four, Blue, Green, Yellow')
);
$searchTerm = 'one two blue four';
$rs = new OccurrenceSorter();
$sortedArr = $rs->sort($arr, $searchTerm);
var_dump($sortedArr);
请注意,我在abouth示例中使用substr_count()
。因此字符串
two four, four, four, Blue, Blue, Green, Yellow
比下面的字符串“高”(altough这个字符串占地不同搜索词):
One two four, Blue, Green, Yellow
在总的第一个字符串有6场比赛(二,四,四,四,蓝,蓝),第二个则有四场比赛(一,二,四,蓝)。如果这不是所希望的行为,请使用strpos()
。然后,您可以使用substr_count()
,如果strpos()
的a
和b
是相同的,可以获得比另一个更高的排名。
这几乎令人敬畏(我错误地指出了错误),非常感谢你,试图理解这段代码中发生了什么,或许会出现一些问题 – caramba