I think you should avoid regexp at all costs. A few cases you should (could):
- You are an expert at regexp. If you are you, then you should probably use a regex because it is likely to be faster and shorter. Although readability will come down in my opinion.
- You need to increase productivity.
Otherwise, my advice is not to use it!
In any of these cases, I want to determine if x and y are numbers, and if there is an “/” between them. Hopelessly in regex, please help
How to solve your problem:
<?php
class Verify {
public static function numbers($str) {
$explode = explode("/", $str);
foreach($explode as $elm) {
if (!filter_var($elm, FILTER_VALIDATE_INT)) {
return false;
}
}
return true;
}
}
class StackTest extends PHPUnit_Framework_TestCase {
public function testBothPartsAreNumbers() {
$array = array(
"1/2",
"1 / 2",
"1/ 2",
"1 /2"
);
foreach($array as $elm) {
$this->assertTrue(Verify::numbers($elm));
}
}
public function testOneOfThemMightBeNotANumber() {
$array = array(
"1/a",
"a/1",
"1 / a",
"b/2",
"b/a",
"1/2.1",
);
foreach($array as $elm) {
$this->assertFalse(Verify::numbers($elm));
}
}
}
?>
alfred@alfred-laptop:~/php/stackoverflow/4916920$ php -v
PHP 5.3.3-1ubuntu9.3 with Suhosin-Patch (cli) (built: Jan 12 2011 16:08:14)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
alfred@alfred-laptop:~/php/stackoverflow/4916920$ phpunit NumberTest.php
PHPUnit 3.5.10 by Sebastian Bergmann.
..
Time: 0 seconds, Memory: 3.50Mb
OK (2 tests, 10 assertions)
source
share