从行尾的括号中获取百分比值

Get percentage value out of bracket at end of line

我得到了一个像

这样的字符串
Just a text (12%)

现在我想获取百分比值并删除括号。到目前为止,我得到了这个正则表达式:

$result = array();
$content = preg_replace_callback('~\(([^)]*)\)~', function ($m) use (&$result) {
    $percentage = $m[1]/100;
    return '';
}, $content);
echo trim($content)."|".$percentage;

这应该给我输出 Just a text|0.12。当前的正则表达式不删除 % 字符。

更新

而且我需要检查百分比值是否为正确的整数 - 有时

text (10-15%)

在这种情况下,根本不应该发生任何事情。字符串保持原样。

% 放入您的正则表达式中:

$result = array();
$content = preg_replace_callback('~\((\d+)%\)~', function ($m) use (&$result) {
//                                 here __^
    $percentage = $m[1]/100;
    return "|".$percentage;
}, $content);
echo trim($content);

您需要将 $percentage var 作为闭包的引用传递,以便您稍后可以使用它。

$content = preg_replace_callback('~\(([^)]*)\)~', function ($m) use (&$result, &$percentage) {
    $percentage = $m[1]/100;
    return '';
}, $content );