提问者:小点点

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


PHP中,我想读取字符串中的一个特定值,并返回它的值:

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

String1 to Search for: "email = test@gmail.com"         //return =
String2 to Search for: "age > 20"                       //return >

有人知道获取这些值的最简单方法吗? 如果有一个更好的解决数组,请让我知道太。

非常感谢


共3个答案

匿名用户

我认为ju应该使用strpos(string$haystack,mixed$needel[,int$offset=0])。

就像(strpos(“email=test@gmail.com”,'=')===false){do nothing}else{do something}

匿名用户

您可以使用regex

if(preg_match('^(?<left>\w+?) (?<operator>[=><]=?) (?<right>\w+?)$', $string, $matches)) {
    var_dump($matches)
}

//will output
Array
(
    [0] => email = test@gmail.com
    [left] => email
    [1] => email
    [operator] => =
    [2] => =
    [right] => test@gmail.com
    [3] => test@gmail.com
)

因此您可以简单地将$matches['left']用于公式的左边部分。 $matches['right']表示右部分,运算符为$matches['operator']

匿名用户

我想我找到了一个解决办法:

$arrayz = str_split($string);
$operatorsarr = array('=', '>', '<', '>=', '<=');
$matches = array_intersect($arrayz, $operatorsarr);

foreach ($matches as $op){
                
        $operator = $op;     //*there is only one operator per String     
}