Search code examples
phppreg-match

PHP - delete values within brackets if condition true


I'd like to delete the values within brackets only if it contains "eur" AND "%" but have a hard time getting started as exploding the string by "(" didn't get me far.

Example:

"T-Shirt(grey)(20EUR excl.10% discount)with print" -> "T-Shirt(grey)with print"  

"Jacket(blue)" -> "Jacket(blue)"

My initial attempt:

$string="T-Shirt(grey)(20EUR excl.10% discount)with print";

$string = explode("(",$string);
foreach($string as $first){
    if(strlen(stristr($first,'eur'))!=0 AND strlen(stristr($first,'%'))!=0){

    }
}   

Solution

  • I see no preg_match in your code :), but here is an example to get you started:

    $e = '#\([0-9]+(EUR).+(\%)(|.+?)\)#';
    
    $lines = [
    "T-Shirt(grey)(20EUR excl.10% discount)with print",
    "T-Shirt(grey)(20USD excl.10% discount)with print",
    "T-Shirt(grey) with no print",
    "Some weird dress(black)(100EUR with 0% discount)",
    ];
    foreach ($lines as $line)
    {
            if(preg_match($e,$line,$m))
            {
                    print $line. " => " . str_replace($m[0],'',$line)."\n";
            }
    }
    

    Will produce:

    T-Shirt(grey)(20EUR excl.10% discount)with print => T-Shirt(grey)with print
    Some weird dress(black)(100EUR with 0% discount) => Some weird dress(black)