user3142695
user3142695

Reputation: 17332

split a string which consists decimals instead of integer

I split a string '3(1-5)' like this:

$pattern = '/^(\d+)\((\d+)\-(\d+)\)$/';
preg_match($pattern, $string, $matches);

But I need to do the same thing for decimals, i.e. '3.5(1.5-4.5)'. And what do I have to do, if the user writes '3,5(1,5-4,5)'?

Output of '3.5(1.5-4.5)' should be:

$matches[1] = 3.5
$matches[2] = 1.5
$matches[3] = 4.5

Upvotes: 1

Views: 50

Answers (2)

hwnd
hwnd

Reputation: 70732

You can use the following regular expression.

$pattern = '/^(\d+(?:[.,]\d+)?)\(((?1))-((?1))\)$/';

The first capturing group ( ... ) matches the following pattern:

(           # group and capture to \1:
  \d+       #   digits (0-9) (1 or more times)
  (?:       #   group, but do not capture (optional):
    [.,]    #     any character of: '.', ','
    \d+     #     digits (0-9) (1 or more times)
  )?        #   end of grouping
)           # end of \1

Afterwords we look for an opening parenthesis and then recurse (match/capture) the 1st subpattern followed by a hyphen (-) and then recurse (match/capture) the 1st subpattern again followed by a closing parenthesis.

Code Demo

Upvotes: 7

CptVince
CptVince

Reputation: 89

This pattern should help:

^(\d+\.?\,?\d+)\((\d+\,?\.?\d+)\-(\d+\.?\,?\d+)\)$

Upvotes: -1

Related Questions