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.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php function limit_word($str, $len) { if (strlen($str) < $len) return $str; $str = substr($str,0,$len); if ($spc_pos = strrpos($str," ")) $str = substr($str,0,$spc_pos); return $str . "Read more..."; } ?> |
You May Also Like This:
- Limit number of login attempt using PHP & MySQL
- Take Image Snapshot from a webcam with Jquery and HTML
- Pure CSS Animated Background
- How to decode JSON data and accessing the results in PHP
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php include "function.php"; ?> <!DOCTYPE html> <html> <head> <title>Limit the number of words in a div</title> </head> <body> <div class ="text"> <p> <?php echo limit_word('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 150); ?> </p> </div> </body> </html> |
The below code will limit to show only 150 characters from your string and after that, it will put this Read more...
1 2 3 |
<?php echo limit_word('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 150); ?> |
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.