Table of contents

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

 

Feel free to use or modify.

 

I hope it helps. Thank you for reading.

 

Happy coding :)