How to use substr() method In PHP
The substr() function can be used to extract the specified string within the specified limits. The starting and ending indexes are specified and the equivalent number of characters between the start and end length are extracted.
substr(string, start, end)
Parameters:
- string – The string to extract the substring from.
- start – The starting index to extract the string from.
- end – The ending index to extract the string.
Example:
<?php
$string = "Geeks for geeks is fun";
echo("Original String : ");
echo($string . "\n");
echo("Modified String : ");
if (strlen($string) > 10)
$new_string = substr($string, 0, 10) . '!!!';
echo($new_string . "\n");
?>
Output:
Original String : Geeks for geeks is fun
Modified String : Geeks for !!!
How to limit string length in PHP ?
A string is a sequence of characters in PHP. The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted.
Table of Content
- Using for loop
- Using mb_strimwidth() function
- Using substr() method
- Using Regular Expressions with preg_match()
- Using substr_replace() for truncation with ellipsis