regex for preg_match_all仅在字符串中获取10个字符

时间:2018-09-11 01:14:54

标签: php regex preg-match-all

使用下面的代码,如何只为地址中具有preg_match_all和正则表达式的10个字符的用户获取结果数组?

这是我的代码

$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

1 个答案:

答案 0 :(得分: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
        )

)

Repl