Chris
Chris

Reputation: 4728

PHP regex to extract two words

I am trying to get the numeric values from a string. Ideally an array containing both numbers.

I am using this PHP but it only seems to match the first one and not the second.

$str = 'The address has changed from #1216640 to #1218908';

    preg_match_all(
    '/The address has changed from #(.+?) to #(.+?)/s',
    $str,
    $output,
    PREG_SET_ORDER
    );

print_r($output);

What I would like is an array that returns 1216640 and 1218908

Upvotes: 0

Views: 69

Answers (2)

Valentin Mercier
Valentin Mercier

Reputation: 5326

This is the reg ex you are looking for

/The address has changed from #([0-9]+) to #([0-9]+)/s

See the screenshot below: enter image description here

Upvotes: 3

hwnd
hwnd

Reputation: 70722

You can use the following, just search for the numbers followed by # in the string.

$string = 'The address has changed from #1216640 to #1218908';
preg_match_all('/#([0-9]+)/', $string, $matches);
print_r($matches[1]);

Output

Array
(
    [0] => 1216640
    [1] => 1218908
)

Upvotes: 4

Related Questions