I’m trying to pull two numbers from a variable($text) and then multiply them and output the results. The two numbers can be ints and floats.
When I try:
$text = “1 photograph – b&w – 2 x 5 in.”
I get: The image area is 10
Which is what I want
<?php $text = "1 photograph - b&w - 2 x 5.5 in."; if (preg_match("/[[:digit:]]* x [[:digit:]]* /", $text, $match)) : print_r($match); $dimensions = trim($match[0]); $dimensions = explode(" x ",$dimensions); $image_area = (($dimensions[0]) * ($dimensions[1])); echo 'The image area is '.($image_area); endif; ?>
But when I try:
$text = “1 photograph – b&w – 2 x 5.5 in.”
I get a blank screen
How would I output floats?
my code and output:http://sandbox.onlinephpfunctions.com/code/4b45219fdcb7864442268459621bb506c24ce78f
Advertisement
Answer
You have an extra space at the end of the regex, which would break it. Remove it, and it would match 2 x 5
. You should be able to extend it further by adding .
to each side of the regex:
if (preg_match("/[[:digit:].]* x [[:digit:].]*/", $text, $match)) {