8

Possible Duplicate:
RegEx match open tags except XHTML self-contained tags

I have the following string:

$str = " 
<li>r</li>  
<li>a</li>  
<li>n</li>  
<li>d</li>  
...
<li>om</li>  
";

How do I get the HTML for the first n-th <li> tags?

Ex : n = 3 ; result = "<li>r<...>n</li>;

I would like a regexp if possible.

Community
  • 1
  • 1
johnlemon
  • 20,761
  • 42
  • 119
  • 178
  • 11
    [rant](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Chris Shouts Aug 30 '10 at 20:50
  • 6
    All you need to know can be found here: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – prodigitalson Aug 30 '10 at 20:50
  • 10
    Why all the downvoting? Most newbies *will* make this mistake once (and hopefully only once). Also, OP isn't parsing entire documents, it looks like it's a string of unnested `
  • ` tags. Not a great place to use regex, but it isn't *that* bad either. – FrustratedWithFormsDesigner Aug 30 '10 at 20:57
  • prodigitalson - actually you gave me the best answer I could hope for...how was I supposed to find that just by searching ? – johnlemon Aug 30 '10 at 21:05
  • @FrustratedWithFormsDesigner - Agreed. This is a valid question that deserves an answer. That being said, I am going home to play with my son :) – Chris Shouts Aug 30 '10 at 21:06
  • 2
    This question has been asked soooo many times. Are people not searching? Is it not coming up properly in searches? What is going on? It's been asked at least few times just this afternoon! – webbiedave Aug 30 '10 at 21:10
  • @webbiedave: OP is not parsing an HTML documents with regex, OP is searching a string with only one type of tag, all at the same level (no nesting - which is usually the main problem with regex + HTML). Not really the same. – FrustratedWithFormsDesigner Aug 30 '10 at 21:38
  • @FrustratedWithFormsDesigner: How is there no nesting? His inner html is spelling the word "random" which leads me to believe that anything could be in those tags. – webbiedave Aug 30 '10 at 22:11
  • @webbiedavie: It's a very specific sort of example and he never says "any HTMl" or "other tags an' stuff" which leads me to think he will stick to the example (or similar strings); but fair enough: if OP shows that his other input strings can have nested tags, you get 100 internet points and I'll delete my earlier comment. :) – FrustratedWithFormsDesigner Aug 30 '10 at 22:38