Counting words in PHP

2019-09-02 15:14发布

I have a problem with counting words in PHP, this is my code:

$word=substr(stripslashes(strip_tags($row['short_story'], '<a></a>')), 0,100 )."...";
$tpl->set( '{word}',$word);

on that code i just can show URL links in my result, i need to show complete style and HTML codes, so i changed to this:

$word = substr( stripslashes (strip_tags($row['short_story'], '<a><b><i><u><br></a><div></div>')), 0,400 )."...";

i changed this:

<a></a>

to:

<a><b><i><u><br></a><div></div>

But problem is, i have to set word limit over 400-500 if i want to show my result correct! because with 100 0r 200 word limit, HTML codes will be broken!

My question is, how i can use word count, but counting only numbers and letters? for example in this code:

<div style="color:red;">hello</div>

i need to count only hello word. is that possible?

1条回答
一夜七次
2楼-- · 2019-09-02 16:05

Try the below code: it will work only when you know what tags are included in your string.

<?php
$tag_word = '<div style="color:red;">hello</div>';

// You can add any number of tags ex: strip_tags($tag_word, '<div><a><img><p>');
$word = strip_tags($tag_word, '<div>');
echo count($word);
?>
查看更多
登录 后发表回答