【问题标题】:PHP Return matchs in many different stringsPHP返回许多不同字符串中的匹配项
【发布时间】:2020-03-28 18:15:39
【问题描述】:

我有很多不同的字符串,比如:

php

$names = [
"David England Mancester",
"David France Paris ",
"David Spain",
"Roger Spain",
"Trevor England",
"Trevor Russia Moscow",
"Lucy Russia",
"Richard J. Russia",
"Richard J. England Blyth",
"Richard M. England",
];

我需要的是一种从字符串的开头返回多次出现的匹配项的方法。

php

$result = ["David", "Trever", "Richard J"]

我曾考虑从每个字符串中拆分第一个单词并返回任何计数为 > 1 的单词,但我的问题是它可能不止是第一个单词。

这是一个虚构的示例,真实数据将有大约 400 个字符串,因此如果计算时间很长,这应该不是问题,它只会在应用生命周期中发生一次或两次。

有人可以帮忙吗?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • “从字符串开始”是一个非常模糊的概念——Richard 出现了 3 次,有效吗?
  • 自从我第一次误解了你的问题以来,我已经编辑了我的答案。这就是你要找的东西吗?
  • 马丁,我最初开始数第一个单词,但当我意识到它可能不止是第一个单词时,我就卡住了。
  • @GlenUK 您更改了输入值,但忘记根据它更改最终输出。不应该是$result= [ David England,David France Paris,David,Trevor,Trevor Russia,Richard J., Richard J. England,Richard M.]

标签: php regex string


【解决方案1】:

这里有一个简单的方法来计算数组中每个元素的字数。它考虑到将名称与位置分开,如果再找到一个名称,则最后一个名称将只有一个字符或“。”最后:

<?php
$names = [
    "David England",
    "David France",
    "David Spain",
    "Roger Spain",
    "Trevor England",
    "Trevor Russia",
    "Lucy Russia",
    "Richard J. Russia",
    "Richard J. England",
    "Richard M. England",
];
$counts = [];
$countsWithMoreThanOneElement = [];

foreach ($names as $i => $name) {
    if (trim($name) === '') {
        continue;
    }

    $tmp = explode(' ', $name);

    if (count($tmp) > 1) {
        // Let's check for a dot or a single letter to separate location and names

        $wordWithNames = [];
        $foundMoreThanOneName = false;

        foreach ($tmp as $j => $word) {
            $wordWithNames[] = str_replace('.', '', $word);

            if (strpos($word, '.') !== false || strlen($word) === 1) {
                $foundMoreThanOneName = true;

                break;
            }
        }

        if (!$foundMoreThanOneName) {
            array_pop($wordWithNames);
        }

        $name = implode(' ', $wordWithNames);
    } else {
        $name = $tmp[0];
    }

    if (!isset($counts[$name])) {
        $counts[$name] = 0;
    }

    ++$counts[$name];

    if ($counts[$name] > 1 && !in_array($name, $countsWithMoreThanOneElement)) {
        $countsWithMoreThanOneElement[] = $name;
    }
}

print_r($countsWithMoreThanOneElement);

结果:

Array
(
    [0] => David
    [1] => Trevor
    [2] => Richard J
)

可运行示例: http://sandbox.onlinephpfunctions.com/code/0e384e24f5ec350b4b7b27397ec8aab20515570c

编辑1:对不起,我第一次没有从字符串的开头阅读部分。

编辑 2:我再次误解了问题的另一部分:P 现在它应该可以工作了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2021-12-06
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多