Using PHP to convert a HTML string to an array of text formats

html, php

Solution

It is possible by using 2 approaches.

Your first option is regular expressions. You can parse the text using `preg_match()`. For example, to etract text between tags you can use something like these:

preg_match("@<[^>]>([^<]+)</[^>]>@", $yourHtmltext, $m);
// $m[1] will contain the text between tags
echo $m1;

But it is rather tedious to tokenize the string with regex for complex HTML text with nested tags and attributes.

It would be much better, in my opinion, to use DOM parsing to parse the DOM structure of the HTML text. This approach will enable you to travers the text node by node extracting anything you need - tags, text between tags, tag attrtibites etc. This is a simple example of using PHP's built-in DOMDocument for parsing the HTML text (example taken from php.net):

$myhtml = <<<EOF
<html>
<head>
<title>My Page</title>
</head>
<body>
<p><a href="/mypage1">Hello World!</a></p>
<p><a href="/mypage2">Another Hello World!</a></p>
</body>
</html>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($myhtml);

$tags = $doc->getElementsByTagName('a');

foreach ($tags as $tag) {
       echo $tag->getAttribute('href').' | '.$tag->nodeValue."\n";
}
?>

The extra benefit of using DOM parsing instead of regular expressions would be the ability to parse HTML text of arbitrary complex structure and much easier adoption of your script to possible future changes in HTML text structure or your requirements. Look at the documentation about DOMDocument for further information about the library.

Problem

Given the string: ``` <b>Lorem ipsum dolor sit amet, <i>consectetuer adipiscing</i> elit.</b> Donec odio. Quisque volutpat mattis eros. ``` I need to output an array of: ``` $output = array( array( 'text'=>'Lorem ipsum dolor sit amet, ', 'formats' => array('bold') ), array( 'text'=>'consectetuer adipiscing', 'formats' => array('bold','italic') ), array( 'text'=>' elit.', 'formats' => array('bold') ), array( 'text'=>' Donec odio. Quisque volutpat mattis eros.' ) ); ``` Is this possible? Plausible? Likely?

Original source