使用 preg_match 查找字符串中的百分比值。

问题描述 投票:6回答:6

我想在一串文本中分离出一个百分比值,使用 preg_match 应该很容易,但由于在 preg_match 中使用了百分比符号作为运算符,我无法通过搜索找到任何示例代码。使用 preg_match 应该很容易,但是因为在 preg_match 中,百分号是作为运算符使用的,所以我无法通过搜索找到任何示例代码。

$string = 'I want to get the 10%  out of this string';

我想最终得到的是。

$percentage = '10%';

我猜我需要的是这样的东西:

$percentage_match = preg_match("/[0-99]%/", $string);

我相信有一个非常快速的答案,但我不知道该如何解决!

php regex preg-match
6个回答
6
投票
if (preg_match("/[0-9]+%/", $string, $matches)) {
    $percentage = $matches[0];
    echo $percentage;
}

4
投票

使用regex /([0-9]{1,2}|100)%/. 该 {1,2} 指定匹配一个或两个数字。的 | 说要符合模式 数字100。

[0-99] 你有匹配的 一个 字段 0-9 或个位数 9 已经在你的范围内。

注意:这允许00, 01, 02, 03...09有效。如果您不希望这样,请使用 /([1-9]?[0-9]|100)%/ 强制输入一个数字和一个可选的第二个数字,范围为 1-9


2
投票

为什么不呢?/\d+%/? 简洁明了。


1
投票

词组应该是 /[0-9]?[0-9]%/.

角色类里面的范围只针对1个角色。


0
投票
$number_of_matches = preg_match("/([0-9]{1,2}|100)%/", $string, $matches);

匹配的字符将在 $matches 阵列,特别是 $matches[1].

© www.soinside.com 2019 - 2024. All rights reserved.