Site icon

Limit the number of words in a div using HTML and PHP

Limit the number of words

Today we are going to learn how to Limit the number of words in a div using HTML and PHP. In this blog, we are going to use a custom function to limit the number of words within a div tag. You can limit your text with simple PHP code.  To achieve this we have to first create a PHP file function.php with a function name limit_word(). Create a file function.php and put the below code.
[pastacode manual=”%3C%3Fphp%0D%0Afunction%20limit_word(%24str%2C%20%24len)%20%7B%0D%0A%20%20%20%20if%20(strlen(%24str)%20%3C%20%24len)%0D%0A%20%20%20%20%20%20%20%20return%20%24str%3B%0D%0A%0D%0A%20%20%20%20%24str%20%3D%20substr(%24str%2C0%2C%24len)%3B%0D%0A%20%20%20%20if%20(%24spc_pos%20%3D%20strrpos(%24str%2C%22%20%22))%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%24str%20%3D%20substr(%24str%2C0%2C%24spc_pos)%3B%0D%0A%0D%0A%20%20%20%20return%20%24str%20.%20%22Read%20more…%22%3B%0D%0A%7D%20%20%20%0D%0A%3F%3E” provider=”manual” lang=”default”/]
You May Also Like This:

Now, after creating function.php we will now create an index.php file and put the below code into that file. In this file, we first include our function.php file because we use it here.
[pastacode manual=”%3C%3Fphp%0D%0Ainclude%20%22function.php%22%3B%0D%0A%3F%3E%0D%0A%3C!DOCTYPE%20html%3E%0D%0A%3Chtml%3E%0D%0A%3Chead%3E%0D%0A%3Ctitle%3ELimit%20the%20number%20of%20words%20in%20a%20div%3C%2Ftitle%3E%0D%0A%3C%2Fhead%3E%0D%0A%3Cbody%3E%0D%0A%0D%0A%3Cdiv%20class%20%3D%22text%22%3E%0D%0A%3Cp%3E%0D%0A%3C%3Fphp%20%0D%0Aecho%20limit_word(‘Lorem%20ipsum%20dolor%20sit%20amet%2C%20consectetur%20adipiscing%20elit%2C%20sed%20do%20eiusmod%20tempor%20incididunt%20ut%20%0D%0Alabore%20et%20dolore%20magna%20aliqua.%20Ut%20enim%20ad%20minim%20veniam%2C%20quis%20nostrud%20exercitation%20ullamco%20laboris%20nisi%20ut%20aliquip%20ex%20%0D%0Aea%20commodo%20consequat.’%2C%20150)%3B%20%0D%0A%3F%3E%0D%0A%3C%2Fp%3E%0D%0A%3C%2Fdiv%3E%0D%0A%0D%0A%3C%2Fbody%3E%0D%0A%3C%2Fhtml%3E” provider=”manual” lang=”default”/]
The below code will limit to show only 150 characters from your string and after that, it will put this Read more...
[pastacode manual=”%3C%3Fphp%20echo%20limit_word(‘Lorem%20ipsum%20dolor%20sit%20amet%2C%20consectetur%20adipiscing%20elit%2C%20sed%20do%20eiusmod%20%0D%0Atempor%20incididunt%20ut%20labore%20et%20dolore%20magna%20aliqua.%20Ut%20enim%20ad%20minim%20veniam%2C%20quis%20nostrud%20exercitation%20%0D%0Aullamco%20laboris%20nisi%20ut%20aliquip%20ex%20ea%20commodo%20consequat.’%2C%20150)%3B%20%3F%3E” provider=”manual” lang=”default”/]
That’s it. Now you have successfully created a code to Limit the number of words in a div using HTML and PHP. If you have any doubts or question comment down below.

Thanks for visiting, Keep Visiting.

 

Exit mobile version