skip to Main Content

I have a block of HTML that includes an unordered list of items, followed by a paragraph of text. HTML structure looks something like this:

<ul>
  <li>...</li>
</ul>
<p>...</p>

I need to split this block into separate vars. I was thinking of using explode but not sure if it’s the best option.

$hpcs = explode("</ul>", $html);
$hlst = $hpcs[0];
$hsum = $hpcs[1];

2

Answers


  1. if you want to parse in you should use preg_replace

    from https://gist.github.com/molotovbliss/18acc1522d3c23382757df2dbe6f0134

    function ul_to_array ($ul) {
      if (is_string($ul)) {
        // encode ampersand appropiately to avoid parsing warnings
        $ul=preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $ul);
        if (!$ul = simplexml_load_string($ul)) {
          trigger_error("Syntax error in UL/LI structure");
          return FALSE;
        }
        return ul_to_array($ul);
      } else if (is_object($ul)) {
        $output = array();
        foreach ($ul->li as $li) {
          $output[] = (isset($li->ul)) ? ul_to_array($li->ul) : (string) $li;
        }
        return $output;
      } else return FALSE;
    }
    
    Login or Signup to reply.
  2. Yes, you can use explode to split the HTML block into separate vars. In your code, you are using explode to split the HTML block on the closing tag of the unordered list (</ul>). This will result in an array with two elements: the first element will be the unordered list, and the second element will be the paragraph. You can then assign these elements to the variables $hlst and $hsum respectively.

    $html = '<ul>
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>
    <p>This is a paragraph.</p>';
    
    $hpcs = explode('</ul>', $html);
    $hlst = $hpcs[0];
    $hsum = $hpcs[1];
    
    echo $hlst; // Output: <ul>
    echo $hsum; // Output: <p>This is a paragraph.</p>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search