开发者

REGEX match x times "<li> anything in here </li>"

开发者 https://www.devze.com 2023-03-21 14:09 出处:网络
I have a string like this in PHP <li>bla bla bla bla</li> <li>hello hello</li> <li>the brown fox didnt jump</li>

I have a string like this in PHP

<li>bla bla bla bla</li>
<li>hello hello</li>
<li>the brown fox didnt jump</li>
.
.
.
<li>aaaaaaarghhhh</li>

I want to get a string wich contains the first X li's (li tags included in the result string)

<li>.....first one....</li>
<li>.....second one....</li>
<li>.................</li>
<li>.....X one....</li>

How can this be done with REGEX or something else????

I could remove the

</li>

then explode by

<li>

and get the first X elements of array 开发者_StackOverflow社区and then adding again li tags at beginning and at end of each element, but i think its too dirty...

Any better ideas?


See if this regex works for you (replace the number 2 with the required number of li):

((?:<li>.*?<\/li>){2})


How about parsing it as actual DOM elements using PHP Simple HTML DOM Parser

You can download the script from here: http://sourceforge.net/projects/simplehtmldom/files/

If you load that script in to your current script like this:

include_once("simple_html_dom.php");

Then it's as simple as:

$html = "<li>bla bla bla bla</li>, etc, etc ......";

$list_array = array();

foreach($html->find('li') as $element) {
    $list_array[] = $element->innertext;
}
0

精彩评论

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