php - HTML 字符串中所有字符的字符数,但仅测量 20 个可见单词

标签 php html regex string word-count

我在一个 WordPress 网站上工作,其中一个页面列出了有关公司客户的摘录。

假设我有一个网页,其中可见文本如下所示:

"SuperAmazing.com, a subsidiary of Amazing, the leading provider of
integrated messaging and collaboration services, today announced the
availability of an enhanced version of its Enterprise Messaging
Service (CMS) 2.0, a lower cost webmail alternative to other business
email solutions such as Microsoft Exchange, GroupWise and LotusNotes
offerings."

但假设此文本中可以有 HTML 链接或图像,那么原始 HTML 可能如下所示:

<img src="/images/corporate/logos/super_amazing.jpg" alt="Company
logo for SuperAmazing.com" /> SuperAmazing.com, a subsidiary of
<a href="http://www.amazing.com/">Amazing</a>, the leading
provider of integrated messaging and collaboration services, today
announced the availability of an enhanced version of its Enterprise
Messaging Service (CMS) 2.0, a lower cost webmail alternative to other
business email solutions such as Microsoft Exchange, GroupWise and
LotusNotes offerings."

这是我需要做的:找出前 20 个可见单词中是否有链接。

这些是前 20 个可见词:

"SuperAmazing.com, a subsidiary of Amazing, the leading provider of
integrated messaging and collaboration services, today announced the
availability of an"

我需要计算字符数(包括 HTML)到 20 个可见单词,在本例中为“an”,当然页面上的每个摘录都会有所不同。

(我愿意将“SuperAmazing.com”算作 2 个单词,如果这能让事情变得更容易的话。)

我尝试了一些正则表达式来计算单词,但它们都计算 HTML,而不是可见单词。

那么查找前 20 个可见单词的完整字符数(包括 HTML)的正确正则表达式是什么?

最佳答案

这是一个相当不错的正则表达式,用于匹配前 20 个可见单词:

'~^(?:\s*+(?:(?:[^<>\s]++|</?\w[^<>]*+>)++)){1,20}~'

这匹配 1 到 20 个以空格分隔的标记,其中标记定义为一个或多个不以空格分隔的单词或标记(其中“单词”定义为除空格或尖括号之外的一个或多个字符)。例如,这将是一个标记:

<a href="http://www.amazing.com/">Amazing</a>

...但这是两个标记:

<a href="http://www.superduper.com/">Super Duper</a>

这会将独立标签(如您示例中的 <img> 标签,或任何被空格包围的标签)视为单独的标记,从而忽略计数——它只匹配单词“of”在你的例子中。它也不会正确处理 <br>标签,或像 <p> 这样的 block 级标签和 <table> ,如果它们没有周围有任何空白。只有您自己知道问题的严重程度。

编辑:如果那是孤立的<img>标签是你经常看到的东西,你可以预处理文本以删除它后面的空格。这将有效地将它与第一个后续的“真实”标记合并,从而导致更准确的字符计数。我知道在这种情况下它只会改变一两个字符的计数,但是如果第 20 个单词恰好是“supercalifragilisticexpialidocious”,您可能会注意到其中的区别。 :)

关于php - HTML 字符串中所有字符的字符数,但仅测量 20 个可见单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1376766/

相关文章:

php - 包含动态子数组的数组;只捕获最后一个子数组

php - MySQL : "How to store row from one table(link) to multiple(cateogry) tables."

php - Codeigniter 根据字符串列查询数组数据

javascript - 使用 jQuery 将页面滚动到 div 的底部

C#编程如何通过正则表达式对空格和 ","进行分词?

php - 使用 Javascript 更改 OnClick

html - 如何在计算 css 之前暂停浏览器渲染?

php - 如何通过带有嵌套集模型的 php <ul> <li> 标签自动创建菜单

java - 匹配标签之间的字符串:

java - 正则表达式所有格量词