修改字符串以引用PHP中的引用属性值

时间:2015-07-09 05:02:24

标签: php

我有一个这样的字符串:

Username=bob sirname=the     position=buil=der

我想将其转换为:

Username="bob" sirname="the" position="build=der"

但是问题出在位置的一部分,因为它的值也有=个字符。在添加引号后,我想删除“”中的所有=

1 个答案:

答案 0 :(得分:3)

你走了:

$str = 'Username=bob sirname=the position=buil=der';

//slice your string into parts (separated by spaces) and loop through them
$parts = explode(' ', $str);

foreach ($parts as &$part)
{
    //slice every part to pieces (separated by '=' character)
    $pieces = explode('=', $part);

    //the first piece is the name of your pair
    $name = array_shift($pieces);
    //all the other pieces are joined to make a value of your pair
    $value = implode('', $pieces);
    //you want your pair to look like this: name="value"
    $part = $name . '="' . $value . '"';
}

//join the pairs back to a string, separate them by spaces
$str = implode(' ', $parts);

//output the final string
echo $str;

我明白了:

Username =“bob”sirname =“the”position =“builder”

我相信这就是你所需要的。