PHP Shortcode function in other PHP framework

For example, if your WordPress Shortcode is [my_shortcode], you can use the following code to read this Shortcode from a text string:

$text = ‘This is some text with a [my_shortcode] shortcode.’;
$pattern = ‘/\[my_shortcode\]/’;
preg_match($pattern, $text, $matches);

if (!empty($matches)) {
// Shortcode found, do something with it
echo “Found shortcode: ” . $matches[0];
} else {
// Shortcode not found
echo “Shortcode not found”;
}

and get Attribute

$text = ‘This is some text with a [my_shortcode foo=”bar” baz=”qux”] shortcode.’;
$pattern = ‘/\[my_shortcode\s+([^\]]+)\]/’;
preg_match($pattern, $text, $matches);

if (!empty($matches)) {
// Shortcode found, extract attributes
$attributes_str = $matches[1];
$attributes = array();
$pattern = ‘/(\w+)=”([^”]*)”/’;
preg_match_all($pattern, $attributes_str, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$attributes[$match[1]] = $match[2];
}
print_r($attributes);
} else {
// Shortcode not found
echo “Shortcode not found”;
}

Published
Categorized as wp