PHP fetch a specific value that begins with a given number from a string with letters and numbers?

In PHP, you can extract a specific value that begins with a given number from a string containing letters and numbers using substr() combined with strpos().

Syntax

substr(string, start_position, length)
strpos(string, search_value)

Example

Let's extract a value beginning with "989" from a mixed string −

<?php
    $value = "1045632245555fghjklm67535454663443gfdjkbvc9890000006777743";
    echo "The actual value is: " . $value . "<br>";
    
    // Find position of "989" and extract 16 characters from that position
    $result = substr($value, strpos($value, "989"), 16);
    echo "The filtered value is: " . $result;
?>
The actual value is: 1045632245555fghjklm67535454663443gfdjkbvc9890000006777743
The filtered value is: 9890000006777743

How It Works

The solution works in two steps −

  • strpos($value, "989") − Finds the position where "989" first occurs in the string
  • substr($value, position, 16) − Extracts 16 characters starting from that position

Flexible Length Extraction

To extract all characters from the starting number to the end of string −

<?php
    $value = "abc123def456ghi789xyz";
    $searchNumber = "456";
    
    $position = strpos($value, $searchNumber);
    if ($position !== false) {
        $result = substr($value, $position);
        echo "Extracted value: " . $result;
    } else {
        echo "Number not found";
    }
?>
Extracted value: 456ghi789xyz

Conclusion

Use strpos() to locate the starting position of your target number, then substr() to extract the desired portion. Always check if strpos() returns false to handle cases where the number isn't found.

Updated on: 2026-03-15T09:32:35+05:30

234 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements