PHP 将 [plugin-something] 替换为 include_once
PHP Replace [plugin-something] with include_once
我是 'advanced' PHP 的新手,我已经为这个问题苦苦挣扎了一个星期。我已经阅读了该论坛上的几乎所有内容以找到解决方案,但没有一个效果很好。
我想从数据库中获取内容并将所有文本(如 [plugin-example])替换为 include_once(example.php)
其背后的原因是为内容管理系统制作类似于 'shortcode' 的东西。
我尝试了几个代码,这个是最接近我的解决方案的 (i think/hope)。问题在于,这仅用最后一个匹配值(在本例中为滑块)替换了两个 [plugins]。
<?php
//get database row
while($page = mysqli_fetch_array($hl_page)){
//regex
$search = "/\[plugin-(.*)\]/";
//get all matches with search
$content = htmlspecialchars_decode("This is my blog
[plugin-blog]
And this is my slider
[plugin-slider]");
preg_match_all($search, $content , $matches);
foreach($matches[1] as $match) {
$match;
}
enter code here
//get file
ob_start();
include_once(''.$match.'.php');
$replace = ob_get_contents();
ob_end_clean();
//echo content from page
echo preg_replace($search,$replace,$content);
}?>
该代码输出:
文字内容
[include_once('slider.php')] <---应该是 blog.php
更多文字内容
[include_once('slider.php'] <--- 这个不错
非常感谢所有帮助!
将替换放入 foreach 循环中:
foreach($matches[1] as $match) {
//get file
ob_start();
include_once(''.$match.'.php');
$replace = ob_get_contents();
ob_end_clean();
$content = preg_replace($search, $replace, $content);
}
echo $content;
如果我很清楚你想做什么,更简单的方法是使用 preg_split
:
$content = <<<'EOD'
This is my blog
[plugin-blog]
And this is my slider
[plugin-slider]
EOD;
$parts = preg_split('~\[plugin-([^]]+)]~', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $k => $v) {
if ($k & 1)
include_once("$v.php");
else
echo htmlspecialchars_decode($v);
}
我是 'advanced' PHP 的新手,我已经为这个问题苦苦挣扎了一个星期。我已经阅读了该论坛上的几乎所有内容以找到解决方案,但没有一个效果很好。
我想从数据库中获取内容并将所有文本(如 [plugin-example])替换为 include_once(example.php) 其背后的原因是为内容管理系统制作类似于 'shortcode' 的东西。
我尝试了几个代码,这个是最接近我的解决方案的 (i think/hope)。问题在于,这仅用最后一个匹配值(在本例中为滑块)替换了两个 [plugins]。
<?php
//get database row
while($page = mysqli_fetch_array($hl_page)){
//regex
$search = "/\[plugin-(.*)\]/";
//get all matches with search
$content = htmlspecialchars_decode("This is my blog
[plugin-blog]
And this is my slider
[plugin-slider]");
preg_match_all($search, $content , $matches);
foreach($matches[1] as $match) {
$match;
}
enter code here
//get file
ob_start();
include_once(''.$match.'.php');
$replace = ob_get_contents();
ob_end_clean();
//echo content from page
echo preg_replace($search,$replace,$content);
}?>
该代码输出:
文字内容 [include_once('slider.php')] <---应该是 blog.php 更多文字内容 [include_once('slider.php'] <--- 这个不错
非常感谢所有帮助!
将替换放入 foreach 循环中:
foreach($matches[1] as $match) {
//get file
ob_start();
include_once(''.$match.'.php');
$replace = ob_get_contents();
ob_end_clean();
$content = preg_replace($search, $replace, $content);
}
echo $content;
如果我很清楚你想做什么,更简单的方法是使用 preg_split
:
$content = <<<'EOD'
This is my blog
[plugin-blog]
And this is my slider
[plugin-slider]
EOD;
$parts = preg_split('~\[plugin-([^]]+)]~', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $k => $v) {
if ($k & 1)
include_once("$v.php");
else
echo htmlspecialchars_decode($v);
}