如何匹配%字符旁边的第一个数字?
<?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 :(得分: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
答案 1 :(得分:0)
此正则表达式将匹配(并捕获)'%'符号前面的所有数字:
'/(\d+)%/'
您可以尝试这样的事情:
$string = 'Get 30% off when you spend over £100 on electronics';
preg_match('/(\d+)%/', $string, $matches);
print_r($matches[1]);
如果您的要求更复杂,请告诉我们。
答案 2 :(得分:0)
这似乎可以解决问题:)
if(strpos($string,'%') !== false) {
$regex_percent = "/((\d{1,5})(?:%))/";
preg_match($regex_percent, $string, $matches_off);
$number = $matches_off[2];
return $number;
}