php 删除选定的方括号并忽略其余部分

php remove selected square brackets and ignore the rest

我正在编写自己的自定义短代码。我想替换一个特定的方括号和其中的文本,如果函数退出并包含在我的方括号中的文本,则保留其余部分。例如,如果在我下面的代码中,因为我有一个名为形容词的函数,我想调用该函数并将包含文本形容词的短代码替换为函数形容词的 return 值。

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

如果您正在寻找一种仅用形容词块中的值属性替换形容词块的方法,那么您可以试试这个:

preg_replace('/\[adjective value="([^"]*)"\]/', '');

这是我执行您描述的一般方法。

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

这应该可以做到。只需在括号之间添加静态值。

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

输出:

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

演示:http://sandbox.onlinephpfunctions.com/code/3495d424001f71d360270cb78d767ba7d0ec034b

此解决方案还假定第一个 ] 正在关闭形容词块。如果 value 中可能有 ],则需要对其进行更改。