I am writing my own custom short code. I want to replace a specific square bracket and the text inside them and leave the rest if a function exits with the text contained in my square brackets. For example if in my code below, since I have a function called adjective, I want to call the function and replace the short code containing the text adjective with the return values of the function adjective.
$str = 'The [adjective value="quick"] brown fox [verb value="jumps"] over the lazy dog.';
function adjective($str, array $value) {
//replace the square brackets and text inside the square brackets with the valuem to get new string
$new_str = 'The quick brown fox [verb value="jumps"] over the lazy dog.';
return $new_str;
}
preg_match_all("/\[([^\]]*)\]/", $str, $matches); //extract all square brackets
if (isset($matches[1]) && !empty($matches[1])) {
$short_codes = $matches[1];
foreach ($short_codes as $short_code) {
$params = explode(" ", $short_code);
if (function_exists($params[0])) {
// call the function "adjective" here
$func = $params[0];
unset($params[0]);
$str = $func($str, $params);
var_dump($str);
}
}
}
This should do it. Just add the static value between the brackets.
Output:
Demo: http://sandbox.onlinephpfunctions.com/code/3495d424001f71d360270cb78d767ba7d0ec034b
This solution also presumes the first
]
is closing the adjective block. If thevalue
could ever have a]
in it this will need to be altered.