我想從 php 中的字串中提取百分比,但如果數字不是小數,我會遇到問題。
其實我用這個:
$string = "This is a text with value 10.1%"
preg_match("/[0-9] \.[0-9] %/", $string, $matches);
在這個例子中,一切都很好,因為我可以提取:10.1%
但是有了這個字串:
$string = "This is a text with value 10%"
……什么都沒有回來。
我想用相同的代碼提取 10% 或 10.1%(帶小數)。任何幫助將不勝感激。
uj5u.com熱心網友回復:
嘗試匹配\d (?:\.\d )?%,這使得百分比的小數部分可選:
$string = "This is a text with decimal value 10.1% and non decimal value 5%.";
preg_match_all("/\d (?:\.\d )?%/", $string, $matches);
print_r($matches[0]);
這列印:
Array
(
[0] => 10.1%
[1] => 5%
)
uj5u.com熱心網友回復:
嘗試包括 . 在正則運算式中:
$string = 'I want to get the 10.1% out of this string';
if (preg_match("/[0-9]. %/", $string, $matches)) {
$percentage = $matches[0];
echo $percentage;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/377696.html
標籤:php
