phpregexcharacter-trimming

Removing excess comma in PHP output string


I want to remove the excess comma in my output string inside a parenthesis.

 $data= "item_id IN ( '1','2',) AND nt_id IN ( 'er1','er2',) AND";

I removed the Excess 'AND' by using rtrim funtion.

$trimValues = rtrim($data,'AND') ;

But how can I remove the comma inside a parenthesis?


Solution

  • ,(?=\s*\))
    

    You can use this and replace by empty string.See demo.

    https://regex101.com/r/rkDV4X/1

    $re = '/,(?=\s*\))/';
    $str = 'item_id IN ( \'1\',\'2\',) AND nt_id IN ( \'er1\',\'er2\',) AND';
    $subst = '';
    
    $result = preg_replace($re, $subst, $str);
    
    echo "The result of the substitution is ".$result;