-4

how to check if a string contains numerical value and has a valid measurement unit? like 150ml or 8.9kg. I understand that it's doable in regex but it is not one of my strengths. What I have so far:

$validunit = array('ml', 'g', 'kg', 'lb', 'oz');
$randomstring = '3.2oz';
//check the string for numerical value and unit, display true/false

Thanks in advance.

  • 2
    You are expected to **try to write the code yourself**. After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Sep 18 '17 at 15:36
  • 1
    Why use regex for this? You can just confirm using `substr`: [What's the most efficient test of whether a PHP string ends with another string?](https://stackoverflow.com/questions/619610/whats-the-most-efficient-test-of-whether-a-php-string-ends-with-another-string) and remove the substring match and use `is_numeric` to confirm the remaining string is a numeric value – ctwheels Sep 18 '17 at 15:46
  • Possible duplicate of [javascript regex to return letters only](https://stackoverflow.com/questions/23136947/javascript-regex-to-return-letters-only) – codeMonkey Sep 18 '17 at 16:35

1 Answers1

0
$regex = "/\d+(\.\d+)?(ml|g|kg|lb|oz)/i";
$randomstring = '3.2oz';
if (preg_match($regex, $randomstring)) {
  // true;
} else {
  // false;
}
A. Eaxon
  • 157
  • 2
  • 7