Denis Makula - 1 year ago 86

PHP Question

I'm having a really hard time understanding RegEx in general, so I have no clue how is it possible to use it in such an issue.

So here we have a tuple

`$tuple = "(12342,43244)";`

And what I try to do is get:

`$value_one = 12342;`

So from

`(value_one,value_two)`

`value_one`

I know it can be possible with

`explode( ',', $tuple )`

Answer Source

Here is the simplest `preg_match`

example with the `\(([0-9]+)`

regex that matches a `(`

, and captures into Group 1 one or more digits from `0`

to `9`

range:

```
$tuple = "(12342,43244)";
if (preg_match('~\(([0-9]+)~', $tuple, $m))
{
echo $m[1];
}
```

See the IDEONE demo

Wrapped into a function:

```
function retFirstDigitChunk($input) {
if (preg_match('~\(([0-9]+)~', $input, $m)) {
return $m[1];
} else {
return "";
}
}
```

See another demo

```
function retValues($input) {
if (preg_match('~\((-?[0-9]+)\s*,\s*(-?[0-9]+)~', $input, $m)) {
return array('left'=>$m[1], 'right'=>$m[2]);
} else {
return "";
}
}
$tuple = "(12342,43244)";
print_r(retValues($tuple));
```

Output: `Array( [left] => 12342 [right] => 43244 )`