将 substr 过滤器从字符计数转换为字数计数
我使用下面的 getExcerpt() 函数来动态设置文本片段的长度。但是,我的 substr 方法目前基于字符计数。我想将其转换为字数。我是否需要分离函数,或者是否有可以使用 PHP 方法来代替 substr?
function getExcerpt()
{
//currently this is character count. Need to convert to word count
$my_excerptLength = 100;
$my_postExcerpt = strip_tags(
substr(
'This is the post excerpt hard coded for demo purposes',
0,
$my_excerptLength
)
);
return ": <em>".$my_postExcerpt." [...]</em>";}
}
I'm using the getExcerpt() function below to dynamically set the length of a snippet of text. However, my substr method is currently based on character count. I'd like to convert it to word count. Do I need to separate function or is there a PHP method that I can use in place of substr?
function getExcerpt()
{
//currently this is character count. Need to convert to word count
$my_excerptLength = 100;
$my_postExcerpt = strip_tags(
substr(
'This is the post excerpt hard coded for demo purposes',
0,
$my_excerptLength
)
);
return ": <em>".$my_postExcerpt." [...]</em>";}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 str_word_count
根据参数,它可以返回数字字符串中的单词(默认)或找到的单词数组(如果您只想使用其中的子集)。
因此,要返回文本片段的前 100 个单词:
Use str_word_count
Depending on the parameters, it can either return the number of words in a string (default) or an array of the words found (in case you only want to use a subset of them).
So, to return the first 100 words of a snippet of text:
如果您希望脚本不忽略句号、逗号和其他标点符号,那么您应该采用这种方法。
注:这只是一个例子,希望对您有帮助。如果对您有帮助,别忘了投票。
If you want that your script should not ignore the period and comma and other punctuation symbols then you should adopt this approach.
Note : This is just an example.Hope it will help you.Don't forget to vote if it help you.