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

2023-12-24

我有一些由所见即所得编辑器(WordPress)生成的 HTML。
我想通过仅显示最多 3 行文本(HTML 格式)来显示此 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. 一些列表项

这可以通过正则表达式实现吗?或者还有其他我可以使用的方法吗?
正如所提问和回答的那样,我知道这可以通过 JavaScript 以“hacky”方式实现在这个帖子上 https://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i.
但我想纯粹在服务器端(使用 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;
        }
    }
}

Output:

1. Hello, this is some generated HTML.<br />
2. Some list item<br />
3. Some list item<br />
4. Some list item<br />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 PHP 计算 HTML 代码的行数? 的相关文章