【问题标题】:sorting array with uasort comparing to a string with regex使用 uasort 对数组进行排序,与使用正则表达式的字符串进行比较
【发布时间】:2013-06-06 10:08:22
【问题描述】:

我正在尝试通过使用 uasort 和正则表达式将数组“$refs”与字符串“$term”进行比较来对数组“$refs”进行排序:

这是我的数组:

Array
(
    [0] => Array
        (
            [id] => 71063
            [uniqid] => A12171063
            [label] => Pratique...
        )

    [1] => Array
        (
            [id] => 71067
            [uniqid] => A12171067
            [label] => Etre....
        )
...

和我的代码:

uasort($refs, function ($a, $b) use ($term) {
            $patern='/^' . $term . '/';  

            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label']) )== 0) {
                return 0;
            }

            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label'])) == 1) {
                return -1;
            }
            if ((preg_match($patern, $a['label']) - preg_match($patern, $b['label'])) == -1) {
                return 1;
            }
        });

我只有 0 个喜欢的回报,我的错误在哪里!:/ 谢谢

【问题讨论】:

  • $refs = $a = $b = $term = ???
  • $refs 是数组,$term 是要比较的词
  • 这就像 perl 中的 1-liner。如果有帮助,我可以在 Perl 中写一些东西
  • 是的,为什么不呢,我以它为例。谢谢
  • 工作正常here。我想知道$term 中有什么?如果它包含正则表达式元字符,您可能需要preg_quote 它。

标签: php regex string sorting


【解决方案1】:

不会按所述回答问题,但您可以使用它。它将根据术语与字符串开头的接近程度有效地对结果进行排名。

function ($a, $b) use ($term) {
  return stripos($a, $term) - stripos($b, $term);
}

这只有在所有值都在其中某个地方包含该术语时才有效(例如类似查询的结果)。

测试脚本:

$arr = array("aaTest", "aTest", "AAATest", "Test");
$term = "Test";
uasort($arr, function ($a, $b) use ($term) {
  return stripos($a, $term) - stripos($b, $term);
});

print_r($arr);

测试输出:

Array
(
    [3] => Test
    [1] => aTest
    [0] => aaTest
    [2] => AAATest
)

更新

将代码更改为使用 stripos 而不是 strpos 进行不区分大小写的排序

【讨论】:

  • 但我需要将主题放在开头!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多