如何使用PHP计算HTML代码的行数? [英] How can I count the amount of lines of an HTML code with PHP?
问题描述
我有一个由WYSIWYG编辑器(WordPress)生成的HTML.
我想通过最多显示三行文本(HTML格式)来显示此HTML的预览.
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).
示例HTML:(始终以新行格式)
<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>
我想在这种格式的HTML中最多预览4行文本.
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).
- 您好,这是一些生成的HTML.
- 某些列表项
- 某些列表项
使用Regex可以做到这一点,还是我可以使用其他方法?
我质疑并回答
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?
推荐答案
使用XPath非常简单:
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;
}
}
}
输出:
1. Hello, this is some generated HTML.<br />
2. Some list item<br />
3. Some list item<br />
4. Some list item<br />
这篇关于如何使用PHP计算HTML代码的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!