Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
