Reputation: 67
I trying to get value in 3 dimension measurement like 7.30 x 7.00 x 4.87 mm using pre_match php function.
Here is ree@([0-9\.]+) - ([0-9\.]+) mm x ([0-9\.]+) mm@
anyone can help me to find what wrong with regex.
Upvotes: 1
Views: 105
Reputation: 192
try this code:
preg_match("#[\d]+(\.[\d]+)?\s*x\s*[\d]+(\.[\d]+)?\s*x\s*[\d]+(\.[\d]+)?\s*mm#",$variable);
a dimension value is a floating point number, ie composed of one or more digits followed by [\d]+ optionally one point and one or more digits (.[\d] +)? example: 1.45, 2,...
The whole optionally followed by one or more spaces \s* followed by an x character optionally followed by one or more spaces \s*.
In the end, we add mm chain.
Upvotes: 0
Reputation: 163477
I think the -
should be a x
and the first mm
you try to match is not there so you could remove it:
([0-9\.]+) x ([0-9\.]+) x ([0-9\.]+) mm
Note that [0-9\.]+
could also match ....
If the mm is only at the end, you could also try it like this and repeat the 7.30 x
pattern 2 times and match 4.87 mm
at the end.
You could use a word boundary \b
on the left and the right side.
\b(?:[0-9]+\.[0-9]+ x ){2}[0-9]+\.[0-9]+ mm\b
$re = '@\b(?:[0-9]+\.[0-9]+ x ){2}[0-9]+\.[0-9]+ mm\b@';
$str = 'This is a test 7.30 x 7.00 x 4.87 mm test';
if (preg_match($re, $str, $matches)) {
echo "Match!";
}
Upvotes: 1
Reputation: 1870
You could do this more accurate and also more elegant by using preg_match_all()
preg_match_all('/\d+(?:\.\d+)?/', $input, $matches);
if(count($matches[0]) == 3){
echo 'match!';
}
$matches[0] will output all numbers in an Array
Array
(
[0] => Array
(
[0] => 2.32
[1] => 1
[2] => 3.455
)
)
Upvotes: 0