How can I check if a string has any value like
(xx%)
at the end?
I would like to extract that value (remove it from the string and save the value in a variable)
Example:
Lorem ipsum (34%)
should become
$string = 'Lorem ipsum';
$value = 34;
Using capturing groups:
$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.
}
^(.*)\((\d+)%\)$
Brief explanation ^ * ^
marks the start of line * (.*)
capture the text until a (
* (\d+)%
match at least one number followed by % and capture only the number * \)$
match a )
at the end of line
<?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];
?>
I don't have access to a machine with PHP on it at the moemnt, but this should be darn close to y our answer.
$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;