Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 文章片段模板样式变量的正则表达式_Php_Regex - Fatal编程技术网

Php 文章片段模板样式变量的正则表达式

Php 文章片段模板样式变量的正则表达式,php,regex,Php,Regex,我正在做一个类似的博客管理系统。我允许用户为每个页面定义模板,如博客主页、分类页面和博客条目页面 对于主页和类别列表,我希望用户有一个样式为{#BLOG:PREVIEW:120#}的模板变量,然后它将显示条目的前120个字符 我所尝试的: $content = preg_replace("/{#BLOG:PREVIEW:(.*?)#}/", substr($entry, 0, $1), $template); 但我得到: 分析错误:语法错误,意外的T_LNUMBER,应为T_变量或“$” 您

我正在做一个类似的博客管理系统。我允许用户为每个页面定义模板,如博客主页、分类页面和博客条目页面

对于主页和类别列表,我希望用户有一个样式为
{#BLOG:PREVIEW:120#}
的模板变量,然后它将显示条目的前120个字符

我所尝试的:

 $content = preg_replace("/{#BLOG:PREVIEW:(.*?)#}/", substr($entry, 0, $1), $template);
但我得到:

分析错误:语法错误,意外的T_LNUMBER,应为T_变量或“$”

您需要使用a来完成您想做的事情:

$content = preg_replace_callback("/{#BLOG:PREVIEW:(.*?)#}/", function($arr) uses($entry) {
    return substr($entry, 0, $arr[1]);
}, $template);
如果您没有支持匿名函数的PHP版本:

function template_replace($arr) {
    // This global variable could be replaced with an object member, if inside a class
    global $entry;
    return substr($entry, 0, $arr[1]);
}

$content = preg_replace_callback("/{#BLOG:PREVIEW:(.*?)#}/", 'template_replace', $template);
你可以这样做:

echo preg_replace_callback('~\{#BLOG:PREVIEW:\K\d++~',
    function($nb) use ($entry) {
        return substr($entry, 0, $nb[0]);
    }, $template);

这不起作用,因为您会注意到正则表达式使用的是
$template
变量,而
substr()
使用的是
$entry
变量。