开发者

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:

<p>
text text text
text text text
</p>
<ul>
text text
text t开发者_如何学Goext
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:

  • I don't know how many <ul></ul> tags there might be in total, the function should find all of them
  • All list-entries inside each <ul></ul> WILL be separated by enter (\r\n)

Any ideas?


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"


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);


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.)


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜