Extract numbers after the last hyphen in PHP?

In PHP, you can extract numbers after the last hyphen in a string using various methods. The most straightforward approach is using the explode() function to split the string and access the last element.

Using explode() with Array Index

Split the string by hyphens and access the last element using its index ?

<?php
    $values = "John-45-98-78-7898906756";
    $parts = explode("-", $values);
    $lastNumber = $parts[count($parts) - 1];
    echo $lastNumber;
?>
7898906756

Using array_pop() Method

A more elegant approach using array_pop() to get the last element ?

<?php
    $values = "John-45-98-78-7898906756";
    $parts = explode("-", $values);
    $lastNumber = array_pop($parts);
    echo $lastNumber;
?>
7898906756

Using end() Function

Another method using end() to get the last array element without modifying the array ?

<?php
    $values = "John-45-98-78-7898906756";
    $parts = explode("-", $values);
    $lastNumber = end($parts);
    echo $lastNumber;
?>
7898906756

Using Regular Expression

For a pattern-based approach, you can use regular expressions to match numbers after the last hyphen ?

<?php
    $values = "John-45-98-78-7898906756";
    preg_match('/[^-]*$/', $values, $matches);
    echo $matches[0];
?>
7898906756

Conclusion

The explode() method with array_pop() or end() is the most readable approach. Use regular expressions when dealing with complex patterns or when you need additional validation of the extracted content.

Updated on: 2026-03-15T09:38:54+05:30

918 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements