PHP - 如果条件为真,则删除括号内的值

时间:2015-09-08 08:00:34

标签: php preg-match

我想删除括号内的值,只有它包含"eur" AND "%"但是很难开始,因为"("对字符串的爆炸并没有让我走得太远。

示例:

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

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

我最初的尝试:

$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){

    }
}   

1 个答案:

答案 0 :(得分:0)

我的代码中没有看到preg_match :),但这是一个让你入门的例子:

$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";
        }
}

将产生:

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)
相关问题