PHP属性分析器


PHP Properties Parser

我正在制作一个属性解析器,我希望它能够解析任何长度的字符串。

例如,我希望能够进行以下调用:

getDynamicProp("cheese:no;sauce:yes;chicken:brown", "sauce");

并从中返回CCD_ 1

到目前为止,我得到的是:

function getDynamicProp($string , $property){
        $args = func_num_args();
        $args_val = func_get_args();
        $strlen = mb_strlen($string);

        $propstrstart = mb_strpos($string , $property . ":");
        $propstrend1 = substr($string , $propstrstart , )
        $propstrend = mb_strpos($string , ";" , $propstrstart);

        $finalvalue = substr($string , $propstrstart , $propstrend);
        $val = str_replace($property . ":" , "" , $finalvalue);
        $val2 = str_replace(";" , "" , $val);
        return $val2;
    }

你可以试试这个。该函数使用爆炸将字符串转换为更容易操作的数组:

function getDynamicProp($string , $property){
  $the_result = array();
  $the_array = explode(";", $string);
  foreach ($the_array as $prop) {
    $the_prop = explode(":", $prop);
    $the_result[$the_prop[0]] = $the_prop[1];
  }
  return $the_result[$property];
}
$the_string = "cheese:no;sauce:yes;chicken:brown";
echo getDynamicProp($the_string,"cheese");
echo getDynamicProp($the_string,"sauce");
echo getDynamicProp($the_string,"chicken");

我觉得你把它搞得太复杂了,或者我不明白你想要什么。我将使用regex,而不是进行位置搜索。

以下是我将使用的:

function getDynamicProp($string , $property){
     if (preg_match('/(^|;)' . $property . ':(?P<value>[^;]+)/', $string, $matches)) {
          return $matches['value'];
     }
     return false;
}

检查此处以可视化regex

如果您可以控制这个字符串,那么最好使用json_encodejson_decode。如果不是这样的话就容易多了:

function getDynamicProp($string, $property) {
    $string = str_replace(array(':',';'), array('=','&'), $string);
    parse_str($string, $result);
    return $result[$property];
}

或者将它们存储为cheese=no&sauce=yes&chicken=brown。然后就更容易了。