【问题标题】:regex for preg_match_all to get only 10 chars in string [duplicate]preg_match_all 的正则表达式仅在字符串中获取 10 个字符 [重复]
【发布时间】:2018-09-11 01:14:54
【问题描述】:

使用下面的代码,我怎样才能只为地址中有 10 个字符且带有 preg_match_all 和正则表达式的用户获取结果数组?

这是我的代码

$data = 'Maria address is QwMP_jkRkM and lives in Peru, Joseph address is QMPjkRk2ZM and lives in Peru, Miguel address is Q.wMP_jkRljo_hkM and lives in New York, George address is hdiJoW58_7 and lives in Austria';

preg_match_all('#(.*?) address is (.*?) and lives in (.*?)#', $data, $output);

实际上返回所有匹配项,我需要删除其地址中包含超过 10 个字符的结果。

注意:我不应该使用 foreach

【问题讨论】:

  • {10} - 精确到 10 个字符(而不是 *)。 * 和 ?在一起真的没有意义。 * 匹配 0-无限,?没有一个匹配
  • 你的预期输出是什么?
  • (.*?) address is (.{1,10}) and lives in (.*?) 也许?
  • @Jeff, '?'让它不贪婪。

标签: php regex preg-match-all


【解决方案1】:

约束似乎是人为的,但这应该会产生正确的输出(如果笨拙的话)并且它确实使用了(.*?)

$data = 'Maria address is QwMP_jkRkM and lives in Peru, Joseph address is QMPjkRk2ZM and lives in Peru, Miguel address is Q.wMP_jkRljo_hkM and lives in New York, George address is hdiJoW58_7 and lives in Austria';

preg_match_all('#([^ ]*?) address is (.{1,10}) and lives in (.*?)(?:$|,)#', $data, $output);

print_r($output);

结果:

Array
(
    [0] => Array
        (
            [0] => Maria address is QwMP_jkRkM and lives in Peru,
            [1] => Joseph address is QMPjkRk2ZM and lives in Peru,
            [2] => George address is hdiJoW58_7 and lives in Austria
        )

    [1] => Array
        (
            [0] => Maria
            [1] => Joseph
            [2] => George
        )

    [2] => Array
        (
            [0] => QwMP_jkRkM
            [1] => QMPjkRk2ZM
            [2] => hdiJoW58_7
        )

    [3] => Array
        (
            [0] => Peru
            [1] => Peru
            [2] => Austria
        )

)

【讨论】:

  • 这是正确的正则表达式。 ty
猜你喜欢
  • 2012-03-31
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多