Domanda

I am trying to match all occurrences of {$anything} in a string.

An example string would be:

Hello {$test} World

Which works fine with:

^.*\{\$(.*?)\}.*$

or

preg_match("/^.*\{\$(.*?)\}.*$/", $input_line, $output_array);

But how do I loop this so it retrieves all the matches, for instance if I have:

Hello {$test} World {$done}

It only retrieves the last match into the array:

Array
(
    [0] => Hello {$test} World {$done}
    [1] => done
)
È stato utile?

Soluzione

Use preg_match_all with the correct regex to get all matches with: {$...} pattern

preg_match_all("/\{\$([^}]*)\}/", $input_line, $output_array);

Then iterate through (process) $output_array[1].

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top