I'm looking to analyse strings in PHP. They appear as such:
Premium Upgrade (€10.00)
I want to detect when a string contains '(€10.00)', however the price will change. Hence I'm guessing a RegEx for 'Bracket, Float, Bracket' The end result is I want to remove the price from the string, however, its possible something else may appear in the brackets e.g.
Premium Upgrade (Per Person)
And hence I can't just explode or substring on the first opening brackets. However, there could be two, or more, brackets e.g.
Premium Upgrade (Per Person) (€10.00)
Hence in this instance, I would need to output:
Premium Upgrade (Per Person)
Thus my high level flow would be:
My pysedo code is:
//Get my string
$str = $meta->display_key;
//I need a RegEx here to detect my bracket and float e.g. (€X.YY)
if (strpos($str, '(') !== false) {
//Need to remove brackets and float here, but leave all other brackets in place.
$formatted_string = substr($str, 0, strrpos($str, '('));
}
//Do nothing, the string doesn't match my criteria
else $display_key_formatted = $str;
To delete a price in brackets that is in the (
+CURRENCY_SYMBOL
+FLOAT_OR_INT_NUMBER
+)
you may use
$res = preg_replace('~\s*\(\p{Sc}\d[.\d]*\)~u', '', $s);
See the regex demo
Details
\s*
- 0+ whitespaces\(
- a (
\p{Sc}
- any currency char\d
- a digit[.\d]*
- 0+ chars that are either .
or a digit\)
- a )
See the PHP demo:
$re = '/\s*\(\p{Sc}\d[.\d]*\)/u';
$str = ' TEXT (text) (€10.00)';
$res = preg_replace($re, '', $str);
echo $res; // => TEXT (text)
you're looking for a regex like: !\((.\d+\.\d+\))!
that should match anything with a currency and a price within brackets.