Table of contents

Extract Content Between Keywords using PHP Regex

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 :)