Tags
PHP
Asked 6 years ago
2 Oct 2018
Views 1072
david

david posted

php regular expression to find the number from string

php regular expression to find the number from string
I have trying this :

preg_match ('/[^a-zA-Z0-9]/i', $value)

but not getting number from string with full of number and character .
web-api

web-api
answered Apr 25 '23 00:00

To find a number in a string using regular expressions in PHP, you can use the preg_match() function along with a regular expression pattern. Here's an example code snippet:



Define the string to search for a number
$string = "The total price is $49.99";

// Define the regular expression pattern to match a number
$pattern = "/\d+(\.\d+)?/";

// Search the string for a match using the pattern
if (preg_match($pattern, $string, $matches)) {
    // Output the first matched number
    echo "Number found: " . $matches[0];
} else {
    // No match found
    echo "No number found in the string.";
} 

In this code snippet, the preg_match() f unction is used to search the string for a match using the regular expression pattern /\d+(\.\d+)?/. This pattern matches one or more digits, optionally followed by a decimal point and one or more digits. The resulting match is stored in the $matches array, and the first matched number can be accessed using $matches [0].

Note that this regular expression pattern will match any sequence of digits in the string, including those with a decimal point. If you need to match a specific pattern of digits, you can modify the regular expression accordingly. Additionally, this example assumes that only one number is present in the string. If multiple numbers could be present, you would need to modify the code to handle multiple matches
Post Answer