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

时间:2015-06-24 12:40:44

标签: php regex shortcode

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

$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 个答案:

答案 0 :(得分:2)

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

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

输出:

  

棕色的狐狸[动词值=“跳跃”]超过懒狗。

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

此解决方案还假设第一个]正在关闭形容词块。如果value中有],则需要更改。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

这是我所做的一般方式。

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