PHP 将自定义标签替换为列表标签



我有一个数据库表,它将存储产品的描述。我希望用户能够插入自定义的"[FEATURES]"标签,以便能够快速列出产品的所有功能,或者不必使用所见即所得的编辑器或编写自己的html。因此,如下所示,用户将能够指定开始特征标签和结束特征标签列表,如下所示:

[FEATURES]
Feature # 1 would go here!
Feature # 2 would go here!
Feature # 3 would go here!
Feature # 4 would go here!
Feature # 5 would go here!
[/FEATURES]

因此,如上所示,这是用户指定功能列表的方式,但我希望它们以无序列表输出,如下所示:

<ul>
<li>Feature # 1 would go here!</li>
<li>Feature # 2 would go here!</li>
<li>Feature # 3 would go here!</li>
<li>Feature # 4 would go here!</li>
<li>Feature # 5 would go here!</li>
</ul>

我希望我可以使用简单的str_replace功能

str_replace("n", "<li>", $string)

但我在试图弄清楚如何正确做到这一点时遇到了麻烦。 任何帮助将不胜感激。

编辑: 我忘了在那些 [FEATURES] 标签的外面包含它,周围会有随机描述,我只想要功能列表的输出,而不是接受输出上的任何其他描述。所以我认为preg_match_all功能可能是必要的,只是不太确定如何将它们组合在一起。

解决它有两个部分:

  • 将打开和关闭[FEATURES]分别替换为各自的<ul>
  • 处理所有三个可能的新行:nrrn

亚伦,这是一个基本的解决方案:

<?php
$input = <<<INPUT
[FEATURES]
Feature # 1 would go here!
Feature # 2 would go here!
Feature # 3 would go here!
Feature # 4 would go here!
Feature # 5 would go here!
[/FEATURES]
INPUT;
// Add basic tags
$input = str_replace("[FEATURES]", "<ul>", $input);
$input = str_replace("rn", "</li>n<li>", $input);
$input = str_replace("[/FEATURES]", "</ul>", $input);
// Clear up tags we don't need
$input = str_replace("<ul></li>", "<ul>", $input);
$input = str_replace("<li></ul>", '</ul>', $input);
echo $input;

输出:

<ul>
<li>Feature # 1 would go here!</li>
<li>Feature # 2 would go here!</li>
<li>Feature # 3 would go here!</li>
<li>Feature # 4 would go here!</li>
<li>Feature # 5 would go here!</li>
</ul>

在这里检查它是如何工作的: http://sandbox.onlinephpfunctions.com/code/6cd7fe761f59802c81c8832108c32c9434a4e9f0

  1. 字符串分解成行
  2. <li>标签将每行包围起来
  3. 将所有内容粘合在一起,并用<ul>标签包围物品

法典:

echo "<ul>" . implode('', 
array_map(function ($item){ return '<li>' . $item . '</li>';},
explode("n", $string)
)
)
. '</ul>' ;
<?php
$fts = <<<EOD
[FEATURES]
Feature # 1 would go here!
Feature # 2 would go here!
Feature # 3 would go here!
Feature # 4 would go here!
Feature # 5 would go here!
[/FEATURES]
EOD;
$ul = "<ul>";
foreach(explode("rn", $fts) as $str){
$ul .= !strpos($str, "FEATURES") ? "<li>".$str."</li>" : "";
}
$ul .= "</ul>";
echo $ul;

输出:

<ul>
<li>Feature # 1 would go here!</li>
<li>Feature # 2 would go here!</li>
<li>Feature # 3 would go here!</li>
<li>Feature # 4 would go here!</li>
<li>Feature # 5 would go here!</li>
</ul>

下面是使用正则表达式的解决方案:

<?php
$Input = "";
$Input .= "[FEATURES]n";
$Input .= "Fits in pocketn";
$Input .= "Waterproofn";
$Input .= "2-year warrantyn";
$Input .= "[/FEATURES]";
$NewInput = preg_replace_callback("~[FEATURES]((?:(?![/FEATURES]).)*)[/FEATURES]~is",
function ($Match) {
return preg_replace("~(?<=[rn]|^)([^rn]*)(?=[rn]|$)~is", "<li>$1</li>", preg_replace("~^s|s$~is","",$Match[1]));
}, $Input??"");
$NewInput = "<ul>n".$NewInput."n</ul>";
echo $NewInput;

http://sandbox.onlinephpfunctions.com/code/1d0d622983acfa9f1ad2156939cc435eecc0dd4d

最新更新