How to use Regular Expressions with preg_match() In PHP
Using preg_match() with a regular expression, you can limit the length of a string by matching the first few characters. The pattern /.{0,5}/ captures up to the first 5 characters.
Example:
<?php
// Declaring original string
$string = "Geeks for geeks is fun";
echo("Original String : ");
echo($string . "\n");
// Trimming length of string using regular expressions
preg_match('/^.{0,11}/', $string, $matches);
$new_string = $matches[0] . "!!";
print("Modified String : ");
print($new_string);
?>
Output
Original String : Geeks for geeks is fun Modified String : Geeks for g!!
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