get substring from string in php from first matching

To extract a substring in PHP based on the first occurrence of another matching substring or character, you can use a combination of the built-in functions strpos() and substr(), or the specialized function strstr()

Here are the most common methods:

Method 1: Using strpos() and substr()

This method is highly flexible and works across all PHP versions. strpos() finds the position of the first match, and substr() extracts the desired portion. 

To get the part after the first match:

php

$data = "123_String_with_more_underscores";
$delimiter = "_";

// Find the position of the first occurrence of the delimiter
$pos = strpos($data, $delimiter);

// Check if the delimiter was found (use !== false because position 0 is a valid match)
if ($pos !== false) {
    // Extract the substring starting from the character after the delimiter
    $whatIWant = substr($data, $pos + 1);
    echo $whatIWant; // Output: String_with_more_underscores
} else {
    echo "Delimiter not found.";
}

To get the part before the first match:

php

$data = "johnclark@mail.com";
$delimiter = "@";

// Find the position of the first occurrence
$pos = strpos($data, $delimiter);

if ($pos !== false) {
    // Extract the substring from the beginning (index 0) up to the position of the delimiter
    $whatIWant = substr($data, 0, $pos);
    echo $whatIWant; // Output: johnclark
} else {
    echo "Delimiter not found.";
}

Method 2: Using strstr()

The strstr() function (case-sensitive) returns the entire portion of the string starting from the first occurrence of the specified match. 

  • To get the part from the first match to the end:php$str = "Welcome to GeeksforGeeks"; $match = "Geeks"; $result = strstr($str, $match); echo $result; // Output: GeeksforGeeks
  • For PHP 5.3.0+ (to get the part before the first match), you can pass a third optional parameter true:php$str = "johnclark@mail.com"; $result = strstr($str, "@", true); // The 'true' parameter returns the part *before* the match echo $result; // Output: johnclark  

For a case-insensitive search, use stristr() instead. 

Method 3: Using explode()

If your delimiter is a simple string and you need the portion after it, explode() can split the string into an array. By setting a limit of 2, you only create two elements. 

php

$string = '233718_This_is_a_string';
$delimiter = '_';

// Split the string into a max of 2 elements
$parts = explode($delimiter, $string, 2);

// The second element ([1]) is the part after the first delimiter
if (isset($parts[1])) {
    echo $parts[1]; // Output: This_is_a_string
}



Leave a Reply