-1

我在 php 中有这个字符串,我使用分隔符吗?

前任:

Animal: Dog
Color: white
Sex: male

我需要在 , 和 之后得到animal:这个color:sex:

字符串在类别后有新行

4

4 回答 4

4
<?php

$str = 'Animal: Dog
Color: white
Sex: male';

$lines = explode("\n", $str);

$output = array(); // Initialize

foreach ($lines as $v) {
  $pair = explode(": ", $v);
  $output[$pair[0]] = $pair[1];
}

print_r($output);

结果:

Array
(
    [Animal] => Dog
    [Color] => white
    [Sex] => male
)
于 2013-05-31T06:12:12.710 回答
1

在php中使用explode()函数

$str = 'Animal: Dog';

$arr = explode(':',$str);
print_r($arr);

这里$arr[0] = 'Animal' and $arr[1] = 'Dog'.

于 2013-05-31T06:12:17.517 回答
1

使用preg_match_all

$string = 'Animal: Dog
Color: white
Sex: male';

preg_match_all('#([^:]+)\s*:\s*(.*)#m', $string, $m);
$array = array_combine(array_map('trim', $m[1]), array_map('trim', $m[2])); // Merge the keys and values, and remove(trim) newlines/spaces ...
print_r($array);

输出:

Array
(
    [Animal] => Dog
    [Color] => white
    [Sex] => male
)
于 2013-05-31T06:19:52.443 回答
0
<?php
    $str = "Animal: Dog Color: White Sex: male";
    $str = str_replace(": ", "=",  $str);
    $str = str_replace(" ", "&",  $str);
    parse_str($str, $array); 

?>

然后使用 $array 的键调用该值。

<?php
     echo $array["Animal"]; //Dog
?>
于 2013-05-31T06:18:02.943 回答