如何使用PHP计算HTML代码的行数



我有一些所见即所得编辑器(WordPress(生成的HTML
我想显示此HTML的预览,最多只显示3行文本(HTML格式(。

示例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行的文本。

要显示的示例预览:(数字表示行号,而不是实际输出(。

  1. 你好,这是一些生成的HTML
  2. 某些列表项
  3. 某些列表项

Regex是否可以实现这一点,或者我可以使用其他方法吗
我知道这在JavaScript中是可能的,正如本文中所质疑和回答的那样
但我想纯粹在服务器端(使用PHP(执行此操作,可能使用SimpleXML?

使用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 />

我亲自编写了以下函数,它并不完美,但对我来说很好。

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));
}

使用echo:时返回以下HTML

<p>Hello, this is some generated HTML.</p><ol><li>Some list item<li><li>Some list item</li>

或格式化:

<p>Hello, this is some generated HTML.</p>
<ol>
<li>Some list item<li>
<li>Some list item</li>

浏览器会自动关闭<ol>标记,所以它可以很好地满足我的需求。

下面是一个沙盒示例

最新更新