From 2c7251b2f3146d31095144afc4f1fa0def3a9bfb Mon Sep 17 00:00:00 2001 From: Nicolas Boisselier Date: Wed, 29 Jun 2016 15:31:30 +0100 Subject: [PATCH] str_match --- lib/php/nb.php | 54 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/lib/php/nb.php b/lib/php/nb.php index 8e9d0cd4..c5470a1c 100644 --- a/lib/php/nb.php +++ b/lib/php/nb.php @@ -1,11 +1,19 @@ test()); +/* +if (empty($_SERVER['DOCUMENT_ROOT'])) var_export([ + '~0 : 0' => nb::str_match('~0','0'), + 'null : 0' => nb::str_match('null','0'), + 'null : ""' => nb::str_match('null',''), + '!null : ""' => nb::str_match('!null',''), + '!~zaz : "zaza"' => nb::str_match('!~zaz','zaza'), + '~zaz : "zaza"' => nb::str_match('~zaz','zaza'), + 'za* : "zaza"' => nb::str_match('za*','zaza'), +]); +*/ if (class_exists('NB')) return; class NB { @@ -28,7 +36,7 @@ class NB { ); #public static function zaza() { return (is_object($this) ? 'TRUE' : 'FALSE'); } - public static function test() { return 'TEST'; } + #public static function test() { return 'TEST'; } public function __construct($opt = array()) { foreach ($opt as $k => $v) { if ( ! array_key_exists($k,$this) ) self::bye("Unknow param $k = `$v`"); @@ -529,6 +537,42 @@ class NB { } } + public static function str_match($pattern,$string) { + $match = false; + + // No empty values + if (strcmp($pattern,'')==0 or $pattern=='!' or $pattern=='~') return false; + + // Equal / Not Equal + $equal = '='; + $not = strpos($pattern,'!')===0 ? true : false; + if ($not) $pattern = substr($pattern,1); + + // Regex + if (strpos($pattern,'~')===0) { + $pattern = substr($pattern,1); + $match = preg_match('@'.str_replace('@','\@',$pattern).'@',$string); + + // Match + } elseif(preg_match('/['.preg_quote('*?[]!').']/',$pattern)) { + + #if (strpos($pattern,'*') !== false or strpos($pattern,'') !== false + $match = fnmatch($pattern,$string); + #var_dump($not); + + // Default + } else { + if (strtolower($pattern)=='null') { + $pattern = ''; + if (!$string) $string = 0; + } + #debug("$pattern = $string"); + $match = ($pattern == $string); + } + + return (bool)($not ? !$match : $match); + + } + } # < Class -#die(self::ext2mime('csv')); ?> -- 2.47.3