How to preg_match() a string and output all results into an array?

I want to output all matching results into an array. I'm only able to output one word and not both.

$input = "I like to eat <cookies> with <coke>.";
$output = [];

preg_match('~<(.*?)>~', $input, $output);
echo $output[1];

It should result with something like:

$output = ["cookies", "coke"];

1 answer

  • answered 2018-07-11 03:40 Joseph_J

    You were really close. Use preg_match_all() instead.

    $input = "I like to eat <cookies> with <coke>.";
    $output = [];
    
    preg_match_all('~<(.*?)>~', $input, $output);
    print_r($output[1]);