Search code examples
phpregexpreg-match

PHP Regex for a specific numeric value inside a comma-delimited integer number string


I am trying to get the integer on the left and right for an input from the $str variable using REGEX. But I keep getting the commas back along with the integer. I only want integers not the commas. I have also tried replacing the wildcard . with \d but still no resolution.

$str = "1,2,3,4,5,6";

function pagination()
{
    global $str;
    // Using number 4 as an input from the string
    preg_match('/(.{2})(4)(.{2})/', $str, $matches);
    echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";     
}

pagination();

Solution

  • I believe you're looking for Regex Non Capture Group

    Here's what I did:

    $regStr = "1,2,3,4,5,6";
    $regex = "/(\d)(?:,)(4)(?:,)(\d)/";
    
    preg_match($regex, $regStr, $results);
    print_r($results);
    

    Gives me the results:

    Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )
    

    Hope this helps!