- 6 years ago
- Zaid Bin Khalid
- 20,537 Views
-
11
You can limit string to N number with PHP built-in function. In this tutorial, I am going to show you how you can limit string with (Read More) Button with PHP. The function is substr() which is return a part of a string.
substr ( string $string , int $start [, int $length ] ) : string
This function has 3 parameters.
- The String is the input string.
- If Start is non-negative, the returned string will start at the first position in a string, counting from zero. And if that Start is negative then the first position will start from the end of the string.
- the last parameter is a length, And the length is also positive or negative.
For example, If the starter is positive in the string ‘asdfghjkl‘, the character at position 0 is ‘a‘, the character at position 2 is ‘c‘, and so on. And if it is negative, then the first character ‘l‘ will return and so on.
<?php
$rest = substr("asdfghjkl", -1); // returns "l"
$rest = substr("asdfghjkl", -2); // returns "lk"
$rest = substr("asdfghjkl", -3, 1); // returns "j"
?>
The simple way to limit string up to 20 or N number is given below.
<?php
$string = 'Lorem Ipsum is simply dummy text.';
$string = substr($string,0,11).'...';
?>
You can print a string on the condition base for that you need to use another function strlen(). This function return length of the given string.
strlen ( string $string ) : int
<?php
$string = 'Note: We convert a string into an array with explode function. I do not use explode function then the output will be a string as shown in below example.';
$string = (strlen($string) > 50)?substr($string,0,25).'... <a href="https://learncodeweb.com/php/print-limited-character-with-read-more-button-in-php/">Read More</a>' : $string;
echo $string;
?>
The output will be.
Note: We convert a string… Read More
- 6 years ago
- Zaid Bin Khalid
- 20,537 Views
-
11