Reputation: 7693
The question is extremely easy, but the solution might not.
Let's say this is my text input inside a variable called $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>
tags there might be in total, the function should find all of them<ul></ul>
WILL be separated by enter (\r\n
)Any ideas?
Upvotes: 1
Views: 2676
Reputation: 2504
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"
Upvotes: 1
Reputation: 4500
Using DOM you can do something like that :
<?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());
Upvotes: 0
Reputation: 145482
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.)
Upvotes: 1
Reputation: 134503
This sounds like a case for string manipulation: http://www.w3schools.com/php/func_string_str_replace.asp
Here's my 5 minute solution:
// 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);
Upvotes: 1