php正则表达式匹配键值对

时间:2014-02-11 07:20:31

标签: php regex

我有一个如下字符串。

$string = "height=175cm weight=70kgs age=25yrs"

字符串内容是键值对,每对由Tab分隔。我希望每个键值对作为单独的变量并打印出每个键值。 我已尝试使用以下代码,但我没有得到正确的结果,请在我出错的地方帮助我。

$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "(([^=]*)\s*=\s*(.*))";
if (preg_match($pattern,$string,$match)) {
    echo "<pre>";
    print_r($match);
} else {
    echo "not matche\n";
}

结果:

Array
(
    [0] => height=175cm weight=70kgs age=25yrs
    [1] => height
    [2] => 175cm weight=70kgs age=25yrs
)

3 个答案:

答案 0 :(得分:2)

您可以使用此代码:

$string = "height=175cm weight=70kgs    age=25yrs";
if (preg_match_all('/\s*([^=]+)=(\S+)\s*/', $string, $matches)) {
   $output = array_combine ( $matches[1], $matches[2] );
   print_r($output);   
}

输出:

Array
(
    [height] => 175cm
    [weight] => 70kgs
    [age] => 25yrs
)

答案 1 :(得分:1)

您可以使用:

$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "/(\w+)=(\d+)(\w+)/i";

if(preg_match_all($pattern,$string,$match))
{
     var_dump($match);
}

结果:

array(4) {
  [0]=>
  array(3) {
    [0]=>
    string(12) "height=175cm"
    [1]=>
    string(12) "weight=70kgs"
    [2]=>
    string(9) "age=25yrs"
  }
  [1]=>
  array(3) {
    [0]=>
    string(6) "height"
    [1]=>
    string(6) "weight"
    [2]=>
    string(3) "age"
  }
  [2]=>
  array(3) {
    [0]=>
    string(3) "175"
    [1]=>
    string(2) "70"
    [2]=>
    string(2) "25"
  }
  [3]=>
  array(3) {
    [0]=>
    string(2) "cm"
    [1]=>
    string(3) "kgs"
    [2]=>
    string(3) "yrs"
  }
}

答案 2 :(得分:1)

我已粘贴下面的代码示例,可帮助您解决问题。当然,它的压缩程度不是很高,并且比其他答案的代码行多得多(这些都是很好的答案!)。

我这样做的原因是因为看起来您可能会从一个解释中受益,这个解释会在解决您的问题的过程中一步一步,这样您就可以了解在此过程中发生的事情。

以下是您可以使用的代码:

<?php

$string = "height=175cm\tweight=70kgs\tage=25yrs";

// Divide your string into an array, with each element
// in the array being a string with a key-value pair
$pairs = explode("\t", $string);

// See what the array of pair strings looks like.
// print_r($pairs); 

// Create an array to get it ready to hold key-value pairs.
$results = array();

// For each string in your array, split at the equal sign
// and set values in the $results array.
foreach ($pairs as $pair) {
  $exploded_pair = explode("=", $pair);

  // See what each exploded pair array looks like.
  // print_r($exploded_pair);

  $key = $exploded_pair[0];
  $value = $exploded_pair[1];
  $results[$key] = $value;
}

print_r($results);

这不是使用正则表达式,而是使用PHP中的explode函数。您可以阅读explode found here上的文档。

您说您的输入字符串由制表符分隔,这就是$string的赋值语句具有\t而不是空格的原因。如果您使用空格而不是制表符,请确保更改

$pairs = explode("\t", $string);

$pairs = explode(" ", $string);
相关问题