DEV Community

Cover image for PHP Keyword or Shortcode Extractor Class
Code And Deploy
Code And Deploy

Posted on

PHP Keyword or Shortcode Extractor Class

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/php-keyword-or-shortcode-extractor-class

In this post, I'm sharing how to extract a keyword or shortcode that starts and ends with specific characters. In my current project with Laravel, I'm building an email template module that has a shortcode. And after created and viewing it I want to extract the added shortcodes for the template and show it to the user. So I came up with this code since I tried to search on google I cannot find the same problem so I coded the class below to cater to what I need.

<?php
/**
 * Coded by: Ronard Cauba
 */
class ShortcodeExtractor 
{
    /**
     * @var $opening
     */
    private $start = "{";

    /**
     * @var $closing
     */
    private $end = "}";

    public function extract($content, $result=[]) 
    {
        $startPos = strpos($content, $this->start);
        $endPos = strpos($content, $this->end);

        $out = "";
        if($startPos > 0 && $endPos > 0) {
            $out = substr($content, $startPos, ($endPos - $startPos) + 1);
            $result[] = $out;
            $latestContent = str_replace($out, "", $content);
            return $this->extract(str_replace($out, "", $content), $result);
        }

        return $result;
    }
}

$content = "The {first_name} quick brown {last_name} fox jumps over the lazy dog {email}.";

$result = (new ShortcodeExtractor)->extract($content);

print_r($result);

//result

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

Feel free to use or modify. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/php-keyword-or-shortcode-extractor-class if you want to download this code.

Happy coding :)

Top comments (0)