Reputation: 184
I have seen this question which relevant for me, but I have one additional condition to add and I don't know how to approach that.
\[(.*?)\]
Right now this code will extract everything inside the square brackets, but I wish to extract only numbers.
Assuming I have the following expression [+₪7.00]
, I wish to extract only 7.00
or 7
.
How can I extract only number from square brackets using regular expression?
Edit:
This is what I tried so far:
\[([^\d])\]
[^\d]
suppose to extract only numbers from string, but that doesn't work here.
Also it will give me 700
instead of 7
because of the dot in 7.00
EDIT:
//Add Addons & Prices
if($slug == "addon"){
$temp = explode(',', $value);
$group = [];
foreach($temp as $t){
echo $t;
$regex = "/\[[^][\d]*\K\d+(?:\.\d+)?(?=[^][]*])/";
$price = 0;
$str = $t;
if (preg_match_all($regex, $str, $matches)) {
foreach ($matches[0] as $match => $m) {
$price = $m;
}
}
echo $price;
echo '<br/>';
$g = [
'name' => $t,
'values' => [
[
'id' => 0,
'name' => $t,
'price' => $price
]
]
];
array_push($group, $g);
}
}
Upvotes: 1
Views: 295
Reputation: 627334
To extracrt a single number from in between square brackets, you can use
\[[^][\d]*\K\d+(?:\.\d+)?(?=[^][]*])
See the regex demo. Details:
\[
- a [
char[^][\d]*
- zero or more chars other than [
, ]
and digits\K
- match reset operator that discards all text matched so far from the current overall match memory buffer\d+(?:\.\d+)?
- one or more digits followed with an optional sequence of a .
and one or more digits(?=[^][]*])
- a positive lookahead that requires zero or more chars other than [
and ]
and then a ]
char immediately to the right of the current location.See a PHP demo:
$re = '/\[[^][\d]*\K\d+(?:\.\d+)?(?=[^][]*])/';
$str = 'I have the following expression [+₪7.00], I wish to extract only 7.00 or 7.';
if (preg_match_all($re, $str, $matches)) {
print_r($matches[0]);
}
// => Array( [0] => 7.00 )
Just in case you have multiple numbers to extract...
Then, you can use
(?:\G(?!\A)|\[)[^][\d]*\K\d+(?:\.\d+)?(?=[^][]*])
See this regex demo. (?:\G(?!\A)|\[)
matches the end of the previous successful match or a [
char.
Upvotes: 1