php remove selected square brackets and ignore the rest

232 views Asked by At

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

There are 3 answers

0
chris85 On BEST ANSWER

This should do it. Just add the static value between the brackets.

$str = 'The [adjective value="quick"] brown fox [verb value="jumps"] over the lazy dog.';
echo preg_replace("/\[adjective.*?\]/", '', $str);

Output:

The brown fox [verb value="jumps"] over the lazy dog.

Demo: http://sandbox.onlinephpfunctions.com/code/3495d424001f71d360270cb78d767ba7d0ec034b

This solution also presumes the first ] is closing the adjective block. If the value could ever have a ] in it this will need to be altered.

0
jmrah On

If you are looking for a way to replace the adjective block with just the value attribute in the adjective block, then you can try this:

preg_replace('/\[adjective value="([^"]*)"\]/', '$1');
0
Casimir et Hippolyte On

This is the general way I will do what you describe.

// you build an associative array of functions (a function for each tagName)
$funcs = [ 
    'adjective' => function ($m) {
        // do something, example: $result = $m['attrValue'];
        return $result;
    },

    'verb' => function ($m) {
        // do something
        return $result;
    }, 

    // etc.
];

$str = 'The [adjective value="quick"] brown fox [verb value="jumps"] over the lazy dog.';

$pattern = '~\[(?<tagName>\w+)\s+(?<attrName>[^\s=]+)="(?<attrValue>[^"]*)"\s*]~';

$result = preg_replace_callback($pattern, function ($m) use ($funcs) {
    return $funcs[strtolower($m['tagName'])]($m);
}, $str);