Parse a string with placeholders into an array with PHP
-
10-10-2019 - |
Question
I have a string that like
$input = '%name (%postcode) <%email>';
How can I detect the placeholders with the scheme %NAME
so that I get an array
$wildcards = array('name', 'postcode', 'email');
in the end?
It should recognize any wildcards following the wildcard scheme in any string. So the function should also convert
'%address (%name)'
to
array('address', 'name')
The wildcard scheme is not fixed, so if you have a better solution those can be changed. I fiddled around with sscanf()
, but as the format of the input string varies I need something more flexible and it did not suit my needs.
Solution
This will do the job:
$input = '%name (%postcode) <%email>';
preg_match_all('/%(\w+)/', $input, $m);
$wildcards = $m[1];
print_r($wildcards);
Outut:
Array
(
[0] => name
[1] => postcode
[2] => email
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow