2014-12-02 29 views
0

如何匹配%字符旁邊的第一個數字?正則表達式與給定字符旁邊的第一個數字匹配

<?php 
$string = 'Get 30% off when you spend over £100 on electronics'; 

if(strpos($string,'% off') !== false) { 
     $number = preg_replace("/[^0-9%]/", '', $string); 
     return $number; 
} 

這將返回30%,100

任何幫助將是巨大的在此先感謝。

+0

你想匹配30什麼把戲?我看到你的IF聲明,如果它不等於false。 – alda1234 2014-12-02 20:21:05

回答

0

此正則表達式匹配(和捕獲)全數字 '%' 號之前:

'/(\d+)%/' 

你可以試一下像這樣:

$string = 'Get 30% off when you spend over £100 on electronics'; 
preg_match('/(\d+)%/', $string, $matches); 
print_r($matches[1]); 

請讓我們知道您的要求是否更加複雜。

+0

這將匹配1000000000000%,這不是有效百分比 – abc123 2014-12-02 20:30:20

+0

OP沒有指定有任何範圍,他只是在'%'符號前詢問數字 - 因此我的評論最終:) – ymas 2014-12-02 20:31:19

0

正則表達式:

\d{1,3}% 

解釋:

\d{1,3} match a digit [0-9] 
    Quantifier: {1,3} Between 1 and 3 times, as many times as possible, giving back as needed [greedy] 
% matches the character % literally 
0

這似乎做:)

if(strpos($string,'%') !== false) { 
     $regex_percent = "/((\d{1,5})(?:%))/"; 
     preg_match($regex_percent, $string, $matches_off); 
     $number = $matches_off[2]; 

     return $number; 
    } 
+1

你確定在'%'之前它總是一個整數?例如,你永遠不會有20.5%? – ymas 2014-12-02 20:48:25

相關問題