Extracting an integer from a string in PHP: how to get only digits?
Hello everyone! I'm a beginner in PHP and ran into a problem. I have a string, for example: "Price: 1234 rub." or "Article #5678-90". I need to extract an integer (unsigned) from it, that is, get only the digits, discarding everything else.
I tried using (int), but it only works if the string starts with a digit. If the string is "Price 100", then (int) gives 0, but I need 100. I tried using preg_match with the regex '/\d+/', but I'm not sure if that's correct, especially if there are multiple numbers in the string (for example, "Code 123, price 456").
Please advise how to reliably extract a single integer from a string? Preferably with a code example. Thanks in advance!
Example strings:
- "Order No. 98765"
- "Amount: 1500 rubles"
- "ID: 42"
- "Result: 0 errors"
What is the simplest and most understandable way for a beginner?