Table of contents
The preg_match_all() defines performing a global regular expression match. This PHP function preg_match_all() is the best way to extract content in multiple results between the keyword from start to end. This is useful if you are building a shortcode-based template like email templates and if you want to generate the shortcodes from the template content. In my previous post, I created a class that generate shortcodes but the code was long.
Â
So now I will share how to do it, to shorten my code using preg_match_all().
Â
<?php
$content = 'The {first_name} quick brown {last_name} fox jumps over the lazy dog {email}.';
preg_match_all('/{(.*?)}/s', $content, $match);
print_r($match);
?>
Â
Result:
Array
(
[0] => Array
(
[0] => {first_name}
[1] => {last_name}
[2] => {email}
)
[1] => Array
(
[0] => first_name
[1] => last_name
[2] => email
)
)
Â
Extract and returns the content including the start and end keyword.
print_r($match[0]);
Â
Result:
Array
(
[0] => {first_name}
[1] => {last_name}
[2] => {email}
)
Â
Extract and returns the content between shortcodes.
print_r($match[1]);
Â
Result:
Array
(
[0] => first_name
[1] => last_name
[2] => email
)
Â
That's it I hope it helps. Thank you for reading :)
Read next