从字符串中读取预定义值 (PHP)

PHP,我想读出字符串中的特定值,并返回其值:


predefined Values: '=', '>', '<', '>=', '<=';


String1 to Search for: "email = test@gmail.com"         //return =

String2 to Search for: "age > 20"                       //return >

有人知道获得这些值的最简单方法吗?如果对于数组有更好的解决方案,也请告诉我。



月关宝盒
浏览 94回答 3
3回答

jeck猫

我认为 ju 应该使用 strpos ( string $haystack , mix $needle [, int $offset = 0 ] ) 。就像 if(strpos("email = test@gmail.com",'=' ) === false ) { 不执行任何操作 } else { 执行某些操作 }

慕妹3242003

你可以使用正则表达式if(preg_match('^(?<left>\w+?) (?<operator>[=><]=?) (?<right>\w+?)$', $string, $matches)) {&nbsp; &nbsp; var_dump($matches)}//will outputArray(&nbsp; &nbsp; [0] => email = test@gmail.com&nbsp; &nbsp; [left] => email&nbsp; &nbsp; [1] => email&nbsp; &nbsp; [operator] => =&nbsp; &nbsp; [2] => =&nbsp; &nbsp; [right] => test@gmail.com&nbsp; &nbsp; [3] => test@gmail.com)所以你可以简单地$matches['left']计算方程的左边部分。$matches['right']对于正确的部分,你的操作员是$matches['operator']

慕码人2483693

我想我找到了解决方案:$arrayz = str_split($string);$operatorsarr = array('=', '>', '<', '>=', '<=');$matches = array_intersect($arrayz, $operatorsarr);foreach ($matches as $op){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $operator = $op;&nbsp; &nbsp; &nbsp;//*there is only one operator per String&nbsp; &nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP