I want to create an array from a string that contains brackets like {! !}. However the whitespaces at the beginning and at the end of the encapsulated string should not be displayed.
$string = "{! This should be in the output !} this should not be in the output {!show_in_output!} don't show {! show !}";
preg_match_all("/{!(.*)!}/Us", $string , $output);
The resulting array looks like this:
Array
(
[0] => Array
(
[0] => {! This should be in the output !}
[1] => {!show_in_output!}
[2] => {! show !}
)
[1] => Array
(
[0] => This should be in the output
[1] => show_in_output
[2] => show
)
)
But it should look like this:
Array
(
[0] => Array
(
...
)
[1] => Array
(
[0] => This should be in the output
[1] => show_in_output
[2] => show
)
)
Is there a way to achieve this with a modified regex?
Thank you!
The
(.*)in the middle of/{!(.*)!}/matches any characters between your{!and!}. If you want to NOT capture spaces before and after that, you have to match whitespace and not include the whitespace in your group, so in your case:/{!\s*(.*?)\s*!}/. The?says to make a minimal match of the.*so that it doesn’t include the whitespace that you want matched by the second\s*.