I have a list of params that I get from a specific shortcode I made available for users to provide.
Example of user input: This is my list of names: {{names("John", 'Mike', "O'connor")}}
From that, I have a regex to extract the list of params, so I get a string like: "John", 'Mike', "O'connor"
But now I need to convert this list to an array and the best way I can think is using json_decode, which can break as some users simply use single quotes.
What's the best way to convert this string into an array? Using str_replace to replace ' by " will also break the ' in the "O'connor" param.
What about extracting the names with regex like below?
$re = '/(["\'])((?:(?!\1).)*)\1/';
$str = '{{names("John", \'Mike\', "O\'connor")}}';
preg_match_all($re, $str, $matches, PREG_PATTERN_ORDER, 0);
// Print the entire match result
var_dump($matches);
Outputs:
array (size=3)
0 =>
array (size=3)
0 => string '"John"' (length=6)
1 => string ''Mike'' (length=6)
2 => string '"O'connor"' (length=10)
1 =>
array (size=3)
0 => string '"' (length=1)
1 => string ''' (length=1)
2 => string '"' (length=1)
2 =>
array (size=3)
0 => string 'John' (length=4)
1 => string 'Mike' (length=4)
2 => string 'O'connor' (length=8)
The names are available at $matches[0]
with quotes or at $matches[2]
without quotes.