1

I have a string like:

$string = "P 1 BNN-01 HV A7weg letsel (Auto) A7 Re 138,3 HASKERHORNE.";

I want to get the "138,3" part to use as variable like $number = "138,3". I think I can use preg_match_all and then use the matches array, but I cant find the correct regex for it.

So the string can contain multiple numbers, but I need only the one with a comma in it. It can contain a maximum of 3 numbers before the comma, and only one after.

$pattern = "^-?\d+(,\d+)*(\.\d+(e\d+)?)?$";
if(preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER)) {
    print_r($matches);
}
2
  • 2
    $pattern = '~\d+,\d+~'; and use preg_match since you need a single match. Commented Dec 12, 2022 at 19:09
  • what Wiktor wrote: $number = preg_match('~\d+,\d+~', $string, $matches) ? $matches[0] : null; Commented Dec 12, 2022 at 20:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.