Open In App

How to get string between two characters in PHP ?

A string is a sequence of characters stored in the incremental form in PHP. A set of characters, one or many can lie between any two chosen indexes of the string. The text between two characters in PHP can be extracted using the following two methods : 

Approach 1: Using substr() Method: The substr() method is used to retrieve a substring of the original string. It takes as indexes the start and end indexes and extracts the part of the string lying between the indexes. In order to retrieve the substring from the beginning, the start-index is chosen to be 0. 



substr(string, startIndex, lengthStr)

Parameters: 




<?php
    
// Declaring a string variable
$str = "Hi! This is geeksforgeeks";
echo("Original String : ");
echo($str . "\n");
  
$final_str = substr($str, 4, 7);
  
echo("Modified String : ");
echo($final_str);
?>

Output

Original String : Hi! This is geeksforgeeks
Modified String : This is

Approach 2: Using for loop and str_split() Method: The str_split() method is used to split the specified string into an array, where the elements are mapped to their corresponding indexes. The indexes of the array begin with 0. 

array_split( string )

A loop iteration is performed over the array length. Every time the iteration is performed the index is checked if it lies between the start and end index. If it lies in the range, the character is extracted.  




<?php
  
// Declaring a string variable
$str = "Hi! This is geeksforgeeks";
echo("Original String : ");
echo($str . "\n");
  
// Define the start index
$start = 5;
  
// Define the end index
$end = 8;
$arr = str_split($str);
  
echo("Modified String : ");
  
for($i = 0; $i < sizeof($arr); $i++) {
    if($i >= $start && $i <= $end) {
        print($arr[$i]);
    }
}
?>

Output
Original String : Hi! This is geeksforgeeks
Modified String : his 

Article Tags :