php remove selected square brackets and ignore the rest [on hold]

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


Source: shortcode

Leave a Reply