0

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

1
  • You regex doesn't match. ' ' !== '.' Commented Jan 23, 2019 at 17:41

3 Answers 3

1

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)) {
Sign up to request clarification or add additional context in comments.

Comments

1

The regex expression isn't robust enough to distinguish between whole numbers and decimal numbers. The [[:digit:]] operator only matches characters 0-9.

This site is useful for creating and testing regex:

https://regex101.com/

Comments

1

Your regex does not match. You want:

/\d+(?:\.\d+)? x \d+(?:\.\d+)? /

1 or more digits, (optional: dot, 1 or more digits), space, x, space, 1 or more digits, (optional: dot, 1 or more digits), space

test online

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.