Denis Makula Denis Makula - 5 months ago 11
PHP Question

Pattern Matching for a value in tuple PHP ( Regular Expressions? )

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

I know it can be possible with
explode( ',', $tuple )
and then delete the 1st character '(' out of the 1st element in exploded array, but that seems super sloppy, is there a way to pattern match in this manner in PHP?


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

Or, to get both as an array:

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)";

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