开发者

PHP text to array and with key

I know RegExp not well, I did not succeeded to split string to array.

I have string like:

<h5>some text in header</h5>
some other content, that belongs to header <p> or <a> or <img> inside.. not 开发者_如何转开发important...
<h5>Second text header</h5>

So What I am trying to do is to split text string into array where KEY would be text from header and CONTENT would be all the rest content till the next header like:

array("some text in header" => "some other content, that belongs to header...", ...)


I would suggest looking at the PHP DOM http://php.net/manual/en/book.dom.php. You can read / create DOM from a document.


i've used this one and enjoyed it.

http://simplehtmldom.sourceforge.net/

you could do it with a regex as well.

something like this.

/<h5>(.*)<\/h5>(.*)<h5>/s

but this just finds the first situation. you'll have to cut hte string to get the next one.

any way you cut it, i don't see a one liner for you. sorry.

here's a crummy broken 4 liner.

$chunks = explode("<h5>", $html);
foreach($chunks as $chunk){
  list($key, $val) = explode("</h5>", $chunk);
  $res[$key] = $val;
}


dont parse HTML via preg_match instead use php Class

The DOMDocument class

example:

   <?php      
   $html= "<h5>some text in header</h5>
   some other content, that belongs to header <p> or <a> or <img> inside.. not important...
   <h5>Second text header</h5>";
   // a new dom object 
   $dom = new domDocument('1.0', 'utf-8'); 
   // load the html into the object ***/ 
   $dom->loadHTML($html); 
   /*** discard white space ***/ 
   $dom->preserveWhiteSpace = false; 
   $hFive= $dom->getElementsByTagName('h5'); 
   echo $hFive->item(0)->nodeValue; // u can get all h5 data by changing the index
   ?>

Reference

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜