如何使用预匹配拆分字符串键和值


How to split the string key and values using preg match

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

$string = " username: demo password: 123456789"

我想喜欢这个

[username]=demo
[password]=12346890

改用preg_match_all()

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

演示

它匹配一堆类似单词的东西,

然后是一个冒号和空格,然后是另一堆类似单词的东西。

表达式详细信息

如果需要,也可以使用分解方法。

$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];