phphtmlhtml-parsingtext-extractionlistitem

Get the text value of all <li> tags in an HTML string


I have a string from which I want to parse all <li></li> tags, this is the string.

<li>Want this</li>DON'T WANT THIS<li>Want this</li>DON'T WANT THIS<li>Want this</li>...

This is the code that I'm using:

$my_text= array();
preg_match('/<li>(.*?)<\/li>/', $str, $my_text);

But it doesn't work. When I run it this is my_text array:

[0] => "<li>Want this</li>"
[1] => "Want this"

It only has 2 elements of 1000 of them.


Solution

  • All you need is using preg_match_all() function, Something like this:

    <?php
    
    $str = "<li>Want this</li>DON'T WANT THIS<li>Want this</li>DON'T WANT THIS<li>Want this</li>";
    preg_match_all('/<li>(.*?)<\/li>/', $str, $out);
    echo '<pre>';
    print_r($out);
    

    Online Demo