如何将字符串转换为数组?

How to convert a string to an array?

我有一个 string 这样的:

$str = "<div>
            <b>
                <label>Company-Name : Anything</label>
            </b>
        </div>
        <div>
            <b>
                <label>First-Name : Alex</label>
            </b>
        </div>
        <div>
            <b>
                <label>Cell-Phone : 035123913</label>
            </b>
        </div>";

现在我想要这个数组:

$arr = array ("Company-Name"=>"Anything",
              "First-Name"=>"Alex",
              "Cell-Phone"=>"035123913");

我该怎么做?


据我搜索了解,有一个函数可以删除所有 html 标签:

strip_tags($str);

我认为上面的函数是一个线索。还有两个字符是不变的:\n:。我认为我们可以使用它们来爆炸结果。 (不过我不确定,也许我错了)

您可以使用双 explode

$str = explode(PHP_EOL, $str);
$arr = array();
foreach ($str as $val) {
  $arr[] = explode(":", $val);
}

我猜在所有情况下你可能都需要 trim()

我喜欢 strip_tags 方法,但这是一个正则表达式:

$str = "<div>
            <b>
                <label>Company-Name : Anything</label>
            </b>
        </div>
        <div>
            <b>
                <label>First-Name : Alex</label>
            </b>
        </div>
        <div>
            <b>
                <label>Cell-Phone : 035123913</label>
            </b>
        </div>";

preg_match_all('/<label>(.*)<\/label>/', $str, $matches);
foreach($matches[1] as $match) {
    $parts = explode(':', $match);
    $results[trim($parts[0])] = trim($parts[1]);
}
var_dump($results);

输出:

array (size=3)
  'Company-Name' => string 'Anything' (length=8)
  'First-Name' => string 'Alex' (length=4)
  'Cell-Phone' => string '035123913' (length=9)

这解决了问题,建立在@Praveen Kumar 之前的回答之上

$str = explode(PHP_EOL, $str);
$arr = [];

foreach ($str as $val) {
    $pos=strpos($val, ":");
    if ($pos !== false)
    {
        $arr[] = explode(":", strip_tags($val));
    }

}

foreach($arr as $key=>$value){
   $final_array[trim($value[0])] = trim($value[1]);
}

var_dump($final_array);

输出

   array (size=3)
  'Company-Name' => string 'Anything' (length=8)
  'First-Name' => string 'Alex' (length=4)
  'Cell-Phone' => string '035123913' (length=9)

获得所需结果(不剥离标签)的更简单方法是使用正则表达式:

preg_match_all( "{<label>([^:]+) +: +([^<]+)</label>}", $str, $matches );

这样,在$matches数组中,你会得到:

Array
(
    [0] => Array
        (
            [0] => <label>Company-Name : Anything</label>
            [1] => <label>First-Name : Alex</label>
            [2] => <label>Cell-Phone : 035123913</label>
        )

    [1] => Array
        (
            [0] => Company-Name
            [1] => First-Name
            [2] => Cell-Phone
        )

    [2] => Array
        (
            [0] => Anything
            [1] => Alex
            [2] => 035123913
        )

)