问题
I have some HTML generated by a WYSIWYG-editor (WordPress).
I'd like to show a preview of this HTML, by only showing up to 3 lines of text (in HTML format).
Example HTML: (always formated with new lines)
<p>Hello, this is some generated HTML.</p>
<ol>
<li>Some list item<li>
<li>Some list item</li>
<li>Some list item</li>
</ol>
I'd like to preview a maximum of 4 lines of text in this formated HTML.
Example preview to display: (numbers represent line numbers, not actual output).
- Hello, this is some generated HTML.
- Some list item
- Some list item
Would this be possible with Regex, or is there any other method that I could use?
I know this would be possible with JavaScript in a 'hacky' way, as questioned and answered on this post.
But I'd like to do this purely on the server-side (with PHP), possibly with SimpleXML?
回答1:
It's really easy with XPath:
$string = '<p>Hello, this is some generated HTML.</p>
<ol>
<li>Some list item</li>
<li>Some list item</li>
<li>Some list item</li>
</ol>';
// Convert to SimpleXML object
// A root element is required so we can just blindly add this
// or else SimpleXMLElement will complain
$xml = new SimpleXMLElement('<root>'.$string.'</root>');
// Get all the text() nodes
// I believe there is a way to select non-empty nodes here but we'll leave that logic for PHP
$result = $xml->xpath('//text()');
// Loop the nodes and display 4 non-empty text nodes
$i = 0;
foreach( $result as $key => $node )
{
if(trim($node) !== '')
{
echo ++$i.'. '.htmlentities(trim($node)).'<br />'.PHP_EOL;
if($i === 4)
{
break;
}
}
}
Output:
1. Hello, this is some generated HTML.<br />
2. Some list item<br />
3. Some list item<br />
4. Some list item<br />
回答2:
I have personally coded the following function, which isn't perfect, but works fine for me.
function returnHtmlLines($html, $amountOfLines = 4) {
$lines_arr = array_values(array_filter(preg_split('/\n|\r/', $html)));
$linesToReturn = array_slice($lines_arr, 0, $amountOfLines);
return preg_replace('/\s{2,}/m', '', implode('', $linesToReturn));
}
Which returns the following HTML when using echo
:
<p>Hello, this is some generated HTML.</p><ol><li>Some list item<li><li>Some list item</li>
Or formatted:
<p>Hello, this is some generated HTML.</p>
<ol>
<li>Some list item<li>
<li>Some list item</li>
Browsers will automatically close the <ol>
tag, so it works fine for my needs.
Here is a Sandbox example
来源:https://stackoverflow.com/questions/65205077/how-can-i-count-the-amount-of-lines-of-an-html-code-with-php