如何检查字符串是否具有
之类的值(xx%)
最后?
我想提取该值(将其从字符串中删除并将值保存在变量中)
示例:
Lorem ipsum (34%)
应该成为
$string = 'Lorem ipsum';
$value = 34;
答案 0 :(得分:3)
使用捕获组:
$original = 'Lorem ipsum (34%)';
if (preg_match('/(.*)\s*\((\d+)%\)$/', $original, $matched)) {
$string = $matched[1]; // 'Lorem ipsum'
$value = $matched[2]; // '34'
} else {
// do something else if it does not match.
}
答案 1 :(得分:2)
<?php
$subject = "Lorem ipsum (34%)";
$pattern = '/^([^\(]*)\(([0-9][0-9]?)%\)$/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
$string = $matches[1][0];
$value = $matches[2][0];
?>
我无法在moemnt上访问带有PHP的计算机,但这应该接近我们的答案。
答案 2 :(得分:0)
答案 3 :(得分:0)
$subject = "Lorem ipsum (34%)";
$pattern = '/\(\d\d%\)$/';
preg_match($pattern, $subject, $matches);
if ($matches) { preg_match('/\d\d/', array_pop($matches), $digits); }
if ($digits) {
$value = array_pop($digits);
$string = substr($subject, 0, -5); }
echo $value;
echo $string;