DEV Community

Cover image for How To Extract Content Between Keywords using PHP Regex
Code And Deploy
Code And Deploy

Posted on

How To Extract Content Between Keywords using PHP Regex

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/how-to-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);

?>
Enter fullscreen mode Exit fullscreen mode

Result:

Array
(
    [0] => Array
        (
            [0] => {first_name}
            [1] => {last_name}
            [2] => {email}
        )

    [1] => Array
        (
            [0] => first_name
            [1] => last_name
            [2] => email
        )

)
Enter fullscreen mode Exit fullscreen mode

Extract and returns the content including the start and end keyword.

print_r($match[0]);
Enter fullscreen mode Exit fullscreen mode

Result:

Array
(
    [0] => {first_name}
    [1] => {last_name}
    [2] => {email}
)
Enter fullscreen mode Exit fullscreen mode

Extract and returns the content between shortcodes.

print_r($match[1]);
Enter fullscreen mode Exit fullscreen mode

Result:

Array
(
    [0] => first_name
    [1] => last_name
    [2] => email
)
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/how-to-extract-content-between-keywords-using-php-regex if you want to download this code.

Happy coding :)

Top comments (0)