How to get string between two characters in PHP ?
Last Updated :
17 Jul, 2024
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:
- string: In this parameter, we pass the original string or the string that needs to be cut or modified. It is a mandatory parameter.
- startIndex: It refers to the position of the original string from where the part needs to be extracted. In this, we pass an integer. If the integer is positive it refers to the start of the position in the string from the beginning. If the integer is negative then it refers to the start of the position from the end of the string. This is also a mandatory parameter.
- lengthStr: It is an optional parameter of integer type. It refers to the length of the part of the string that needs to be cut from the original string. If the integer is positive, it refers to start from start_position and extract length from the beginning. If the integer is negative then it refers to start from start_position and extract the length from the end of the string. If this parameter is not passed, then the substr() function will return the string starting from start_position till the end of the string.
PHP
<?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);
?>
OutputOriginal 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
<?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]);
}
}
?>
OutputOriginal String : Hi! This is geeksforgeeks
Modified String : his
Approach 3: Using preg_match()
Using preg_match() in PHP, you can extract a substring between two characters by defining a regular expression pattern that matches the content between the specified delimiters.
Example
PHP
<?php
function getStringBetween($string, $startChar, $endChar) {
$pattern = "/".preg_quote($startChar, '/')."(.*?)".preg_quote($endChar, '/')."/";
preg_match($pattern, $string, $matches);
return $matches[1] ?? '';
}
$string = "Hello [start]World[end]!";
echo getStringBetween($string, "[start]", "[end]") . PHP_EOL; // Output: World
?>
Approach 4: Using strpos() and substr()
The strpos() function is used to find the position of the first occurrence of a substring in a string. By locating the start and end characters' positions, you can then use substr() to extract the substring between these positions.
Example
PHP
<?php
// Declaring a string variable
$str = "Hi! This is geeksforgeeks";
echo("Original String : ");
echo($str . "\n");
// Find the position of the substring "This"
$start_pos = strpos($str, "This");
// If the substring is found, extract it
if ($start_pos !== false) {
$final_str = substr($str, $start_pos, 7);
echo("Modified String : ");
echo($final_str);
} else {
echo("Substring not found.");
}
?>
OutputOriginal String : Hi! This is geeksforgeeks
Modified String : This is
Similar Reads
How to get the last character of a string in PHP ? In this article, we will find the last character of a string in PHP. The last character can be found using the following methods.Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is "Akshit" Its length is 6, in
2 min read
How to get a substring between two strings in PHP? To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples: Input:$string="hey, How are you?"If we need to extract the substring between "How" and "you" then the output should be are Output:"Are"Input:Hey, Welcome to Geeks
4 min read
How to Extract Words from given String in PHP ? Extracting words from a given string is a common task in PHP, often used in text processing and manipulation. Below are the approaches to extract words from a given string in PHP: Table of Content Using explode() functionUsing regular expressionsUsing explode() functionIn this approach, we are using
1 min read
How to get the position of character in a string in PHP ? In this article, we will get the position of the character in the given string in PHP. String is a set of characters. We will get the position of the character in a string by using strpos() function. Syntax: strpos(string, character, start_pos) Parameters: string (mandatory): This parameter refers t
2 min read
How to read each character of a string in PHP ? A string is a sequence of characters. It may contain integers or even special symbols. Every character in a string is stored at a unique position represented by a unique index value. Here are some approaches to read each character of a string in PHPTable of ContentUsing str_split() method - The str_
4 min read
How to remove the first character of string in PHP? Remove the very first character of a given string in PHP Examples: Input : GeeksforgeeksOutput : eeksforgeeksInput :, Hello geek!Output : Hello geek!Explanation:In PHP to remove characters from the beginning we can use ltrim but in that, we have to define what we want to remove from a string i.e. re
3 min read
Extract Substrings Between Brackets in PHP In PHP, extracting substrings between brackets can be done using various approaches. We have to print the word that is present in between the brackets. These are the following approaches: Table of Content Using Regular ExpressionsUsing strpos() and substr() functionsUsing Regular ExpressionsIn this
2 min read
How to replace multiple characters in a string in PHP ? A string is a sequence of characters enclosed within single or double quotes. A string can also be looped through and modifications can be made to replace a particular sequence of characters in it. In this article, we will see how to replace multiple characters in a string in PHP.Using the str_repla
3 min read
How to Convert Special HTML Entities Back to Characters in PHP? Sometimes, when we work with HTML in PHP, you may encounter special characters that are represented using HTML entities. These entities start with an ampersand (&) and end with a semicolon (;). For example, < represents <, > represents >, and & represents &. To co
1 min read
How to check if a String contains a Specific Character in PHP ? In PHP, determining whether a string contains a specific character is a common task. Whether you're validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently. Here are some common a
2 min read