2015-09-08 49 views
1

我想刪除括號內的值,只是它包含"eur" AND "%"但開始時很難,因爲爆炸字符串"("沒有讓我走得很遠。PHP - 如果條件爲真,刪除括號內的值

例子:

"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

請展示一些先前的嘗試。 – mario

+0

你的if語句返回true,所以問題不在這裏。 –

回答

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) 
+0

效果很好!謝謝!只有「歐元」 - 它不應該是 –

+0

是不區分大小寫的,你必須定義(EUR | eur)或類似的東西 - 這就是regexp的用途,畢竟:) –