如何使用preg_match拆分字符串键和值

时间:2014-12-12 09:53:20

标签: php string split preg-match preg-match-all

我想知道如何使用preg_match或任何其他方法将下面的字符串拆分为数组键值,我在阅读电子邮件内容时遇到了问题

$string = " username: demo password: 123456789"

我想要这样

[username]=demo
[password]=12346890

2 个答案:

答案 0 :(得分:3)

改为使用preg_match_all()

if (preg_match_all('/(\w+):\s+(\w+)/', $string, $matches)) {
    $result = array_combine($matches[1], $matches[2]);
}

Demo

它匹配一堆字样的东西,然后是冒号和空格,然后是另一堆字样的东西。

Expression details

答案 1 :(得分:-1)

如果您愿意,也可以使用explode方法。

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

所以你可以......

$string = " username: demo password: 123456789";
$string = trim($string);   //Trim the string for first space like jack said
$stringsplit = explode(" ", $string);

echo $stringsplit[0] . " = " . $stringsplit[1];
echo $stringsplit[2] . " = " . $stringsplit[3];

//then build it to the way you want
//If you need it exactly the way you have it listed above it would be something like..

$stringsplit[0] = str_replace(":", "", $stringsplit[0]);    //these 2 lines only to get
$stringsplit[2] = echo str_replace(":", "", $stringsplit[2]);    //rid of the :

echo "[" . $stringsplit[0] . "]=" . $stringsplit[1];
echo "[" . $stringsplit[2] . "]=" . $stringsplit[3];