[英]how to replace a part of string to create <li> tags using PHP?
The question is extremely easy, but the solution might not. 这个问题非常简单,但解决方案可能并非如此。
Let's say this is my text input inside a variable called $description: 假设这是我在名为$ description的变量中输入的文本:
<p>
text text text
text text text
</p>
<ul>
text text
text text
text text
</ul>
<p>
text text text
text text text
</p>
I believe it's already obvious what I need to do. 我相信我已经很清楚需要做什么。 I need to locate all
<ul></ul>
tags inside my string and add <li></li>
tags for each entry inside, under these conditions: 我需要在字符串中找到所有
<ul></ul>
标签,并在以下情况下为其中的每个条目添加<li></li>
标签:
<ul></ul>
tags there might be in total, the function should find all of them <ul></ul>
标签,该功能应该可以找到所有这些标签 <ul></ul>
WILL be separated by enter ( \\r\\n
) <ul></ul>
内的所有列表条目将由回车( \\r\\n
)分隔。 Any ideas? 有任何想法吗?
This sounds like a case for string manipulation: http://www.w3schools.com/php/func_string_str_replace.asp 这听起来像是字符串操作的情况: http : //www.w3schools.com/php/func_string_str_replace.asp
Here's my 5 minute solution: 这是我的5分钟解决方案:
// Replaces \r\n with </li><li>
$description = str_replace("\r\n\","</li><li>",$description);
// Removes the extra <li> that will be left at the end of every <ul>
$description = str_replace("<li></ul>","</ul>",$description);
// Adds an <li> to the start of the <ul> tag.
$description = str_replace("<ul>","<ul><li>",$description);
If it's such a simple case, you can get away with: 如果是这样简单的情况,您可以摆脱:
$html =
preg_replace_callback('#(?<=<ul>) [^<]+ (?=</ul>)#x', "li", $html);
function li($match) {
foreach (explode("\n", trim($match[0])) as $line) {
$text .= "<li>$line</li>\n";
}
return "\n" . $text;
}
(The callback function needs a better name than "li"
of course.) (当然,回调函数需要比
"li"
更好的名称。)
This will do the job: 这将完成工作:
function addLI ($in) {
$in = str_replace("\r\n", "\n", $in);
$lines = explode("\n", $in);
$out = "";
$ul = false;
foreach($lines as $line) {
if ($ul == false) {
if (stripos($line, "<ul>") !== false) {
$ul = true;
}
}
else {
if (stripos($line, "</ul>") !== false) {
$ul = false;
}
else {
$line = "<li>" . $line . "</li>";
}
}
$out .= $line . "\n";
}
return $out;
}
Edit: first edition worked only with "\\n" - now it works with "\\n" and "\\r\\n" 编辑:第一版仅适用于“ \\ n”-现在适用于“ \\ n”和“ \\ r \\ n”
Using DOM you can do something like that : 使用DOM,您可以执行以下操作:
<?php
$html = '<p>text text texttext text text</p><ul>text text\r\ntext text\r\ntext text</ul><p>text text texttext text text</p>';
$document = new DOMDocument();
$document->loadHTML($html);
$result = $document->getElementsByTagName('ul');
foreach ($result as $item)
{
$liList = explode('\r\n', $item->textContent);
$ulContent = '';
foreach ($liList as $li)
{
$ulContent .= '<li>' . $li . '</li>';
}
$item->nodeValue = $ulContent;
}
echo html_entity_decode($document->saveHTML());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.