How to use preg_match() In PHP

Using `preg_match()` in PHP with the pattern `’/StartHere(.*?)EndHere/’` captures the substring between “StartHere” and “EndHere”. It efficiently extracts content based on defined delimiters, suitable for scenarios requiring flexible and precise substring extraction using regular expressions.

Example:

PHP
<?php
$string = "StartHereHelloWorldEndHere";
$pattern = '/StartHere(.*?)EndHere/';

// Perform the regex match
preg_match($pattern, $string, $matches);

if (isset($matches[1])) {
    echo $matches[1]; // Outputs: "HelloWorld"
} else {
    echo "Substring not found";
}
?>

Output
HelloWorld

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 w3wiki
If we need to get the substring between Welcome and
for then it should be to geeks as for lies within w3wiki.

Output:" to geeks"


Method 1: Firstly you have to find the ending position of the start word. Then find the starting position of the ending word after that return the substring between those indexes. 
Below program illustrate the approach:
Program: 
 

PHP
<?php
    function string_between_two_string($str, $starting_word, $ending_word)
{
    $subtring_start = strpos($str, $starting_word);
    //Adding the starting index of the starting word to 
    //its length would give its ending index
    $subtring_start += strlen($starting_word); 
    //Length of our required sub string
    $size = strpos($str, $ending_word, $subtring_start) - $subtring_start; 
    // Return the substring from the index substring_start of length size 
    return substr($str, $subtring_start, $size); 
}

$str = 'Hey, Welcome to w3wiki';
$substring = string_between_two_string($str, 'Welcome', 'for');

echo $substring;
    
?>

Output: 
 

 to geeks

Similar Reads

Method 2: Using the explode() function.

The explode function splits the given string on the basis of the parameter provided i.e. the separator. Syntax:...

Using preg_match()

Using `preg_match()` in PHP with the pattern `’/StartHere(.*?)EndHere/’` captures the substring between “StartHere” and “EndHere”. It efficiently extracts content based on defined delimiters, suitable for scenarios requiring flexible and precise substring extraction using regular expressions....

Contact Us