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.

<?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:

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.

<?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...

<?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.

 

0 Comments

No Comment.