gpt4 book ai didi

PHP preg_match_all 在匹配项上运行 php 函数

转载 作者:搜寻专家 更新时间:2023-10-31 22:12:50 24 4
gpt4 key购买 nike

我不确定术语,所以我提前道歉。

我正在尝试创建一个 PHP 模板引擎,它将查询 <ZONE header> 的字符串和 </ZONE header>它将拉取介于两者之间的所有内容,然后运行一个 php 函数来查看 header 是否存在。如果标题存在,它将显示中间的内容,如果标题不存在,它将删除中间的内容。

这是一个例子:

$string = "
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<ZONE header><img src="images/header.jpg" /></ZONE header>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
";

该函数理想情况下会删除 <ZONE header><img src="images/header.jpg" /></ZONE header>然后它将运行我创建的 php 函数 header()它检查数据库中是否存在“ header ”,如果存在,它将显示 <ZONE header></ZONE header> 中的所有内容如果没有,它将把它从字符串中删除。

如果“header”存在:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<img src="images/header.jpg" />
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>

如果“header”不存在:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>

这是我正在使用但卡住了的内容:

        preg_match_all("|\<ZONE_header>(.*)\<\/ZONE_header>|isU", $string, $zone, PREG_SET_ORDER);

if (isset($zone) && is_array($zone)) {
foreach ($zone as $key => $zoneArray) {
if ($key == 0) {
$html = $zoneArray[1];
if ($html != "") {
if (header() != "") {
$html = str_replace($zoneArray[0], NULL, $html);
}
}
}
}
}

echo $html;

有什么想法、想法、建议吗?感谢您提供的所有帮助!

最佳答案

请注意,我用 get_header() 替换了您的 header() 函数。

$string = preg_replace_callback('/<ZONE header>(.+)<\/ZONE header>/', 'replace_header', $string);

function replace_header($matches) {
return get_header() ? $matches[1] : '';
}

请参阅 preg_replace_callback 的文档.

关于PHP preg_match_all 在匹配项上运行 php 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10697756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com