如何获取标签之间的自定义标签和值的值

时间:2012-11-19 05:58:36

标签: php regex arrays

我们的想法是从以下字符串中获取值。

String: Server has [cpu]4[cpu] cores and [ram]16gb[ram]

我需要动态获取标签值以及标签之间的内容:[*]*[*]

之间的内容无关紧要

输出:应该是一个数组如下

Array(
    'cpu' => 4,
    'ram' => '16gb'
)

正则表达式模式遇到很多麻烦。任何帮助将不胜感激。

编辑:标签或标签本身之间的值可以是任何字母 - 字母数字或数字。

示例字符串仅为示例。标签可以无限次出现,因此需要动态填充数组 - 而不是手动填充。

4 个答案:

答案 0 :(得分:4)

我的PHP很生疏,但也许:

$str = "Server has [cpu]4[cpu] cores and [ram]16gb[ram] and [memory]2tb[/memory]";
$matches = array();
preg_match_all('/\[(\w+)\]([^\[\]]+)\[\/?\w+\]/', $str, $matches);
$output = array_combine($matches[1], $matches[2]);

详细说明:

  • []以外的任何内容都可以作为代码显示在[]中。
  • []之外的任何内容都可以是代码
  • 的值
  • 结束标记不需要与起始标记匹配。您可以使用反向引用,但它会区分大小写。

答案 1 :(得分:1)

$string = '[cpu]4[cpu] cores and [ram]16gb[ram]';

preg_match('|\[([^\]]+)\]([^\[]+)\[/?[^\]]+\][^\[]+\[([^\]]+)\]([^\[]+)\[/?[^\]]+\]|', $string, $matches);
$array = array($matches[1] => $matches[2], $matches[3] => $matches[4]);

print_r($array);

答案 2 :(得分:1)

工作代码,walkerneo的略微修改版本:

其他人可以建立我的代码或建议我做一些更好的事情:

<pre><?php
    $string = "Server has [cpu]4[cpu] cores and [ram]16gb[ram] and [memory]2tb[/memory]";
    $matches = array();
    $pattern = '/\[(\w+)\]([^\[\]]+)\[\/?\w+\]/';
    preg_match_all($pattern, $string, $matches);
    $output = array_combine($matches[1], $matches[2]);
    var_dump($output);
?></pre>

小提琴:http://phpfiddle.org/main/code/n1i-e1p

答案 3 :(得分:0)

如果允许使用多个preg_match,这可能是一个解决方案:

    $str = '[cpu]4[cpu] cores and [ram]16gb[ram][hdd]1TB[hdd]asdaddtgg[vga]2gb[vga]';
    $arrResult = array();
    preg_match_all('/(\[[A-Za-z0-9]+\][A-Za-z0-9]+\[[A-Za-z0-9]+\])/i', $str, $match,PREG_SET_ORDER);
    if (is_array($match)) {
        foreach ($match as $tmp) {
            if (preg_match('/\[([A-Za-z0-9]+)\]([A-Za-z0-9]+)\[([A-Za-z0-9]+)\]/', $tmp[0], $matchkey)) {
                $arrResult[$matchkey[1]] = $matchkey[2];
            }
        }
    }

    var_dump($arrResult);

结果:

array(4) {
  'cpu' =>
  string(1) "4"
  'ram' =>
  string(4) "16gb"
  'hdd' =>
  string(3) "1TB"
  'vga' =>
  string(3) "2gb"
}