2013-05-31 30 views
-1

我有這個字符串在PHP中我使用分隔符嗎?如何獲得符號後的字符串

例:

Animal: Dog 
Color: white 
Sex: male 

我需要後animal:color:sex:得到了這個詞。

字符串有類別後,新的生產線

+6

提示:您可能需要使用類似['explode'](http://php.net/手冊/ en/function.explode.php):) – summea

回答

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 
) 
+0

這符合我的需求。感謝兄弟,也非常感謝所有誰分享他們的代碼.. – JokeSparrow

+0

@ user2439219接受答案,如果你有時間;) – kevinamadeus

1

使用explode()函數在PHP

$str = 'Animal: Dog'; 

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

這裏$arr[0] = 'Animal' and $arr[1] = 'Dog'.

+0

'$ arr [1]'在這種情況下''狗',實際上,由於那裏的空間。 ;) – doppelgreener

+0

如果你不想要的空間,你可以使用修剪()@JonathanHobbs Hobbs –

+0

我知道,但從技術上講,這將是一個非常有點誤導,是一個新手想知道爲什麼他們的版本有在那裏的空間。 – doppelgreener

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 
?> 
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 
) 
相關問題