-2

Using my code bellow, How can I get results array only for users who have 10 chars in address with preg_match_all and regular expressions?

this is my code

$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);

Actually returns all matches, I need to remove the results that contain more than 10 characters in their address.

Note: I should not use foreach

jhpratt
  • 6,841
  • 16
  • 40
  • 50
jose sanchez
  • 51
  • 1
  • 9

1 Answers1

1

The constraints seem artificial, but this should produce the correct output (if awkwardly) and it does use (.*?):

$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);

Result:

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
        )

)
ggorlen
  • 44,755
  • 7
  • 76
  • 106