2012-12-11 45 views
0

以下是保存联系人信息的字符串。这个字符串是动态的,即有时候是新的字段,例如:手机号码可能会加起来,或者旧字段说:电话号码可能会删除代码Php字符串爆炸成特定数组

       <?php $str = 
           "tel: (123) 123-4567 
           fax : (234) 127-1234 
           email : [email protected]"; 
           $newStr = explode(':', $str); 
           echo '<pre>'; print_r($newStr); 
           ?> 

输出是:

     Array 
          (
           [0] => tel 
           [1] => (123) 123-4567 
                   fax 
           [2] => (234) 127-1234 
                   email 
           [3] => [email protected] 
          ) 

,但需要输出的格式如下:

     Array 
          (
           [tel] => (123) 123-4567 
           [fax] => (234) 127-1234    
           [email] => [email protected] 
          ) 

我试图在5月的方式爆炸...但没”工作。请指导。

+0

你用分隔符':'爆炸。所以'(123)123-4567'和'fax'之间没有像':'这样的分隔符。所以你们得到了同样的价值。 –

+0

@PankitKapadia我使用什么分隔符shd?我没有找到任何其他有意义的分隔符。 – user1871640

+1

文本中每组值之间是否有换行符?如果是这样,请使用“\ n” – Anton

回答

6
$txt = 
          "tel: (123) 123-4567 
          fax : (234) 127-1234 
          email : [email protected]"; 
$arr = array(); 
$lines = explode("\n",$txt); 
foreach($lines as $line){ 
    $keys = explode(":",$line); 
    $key = trim($keys[0]); 
    $item = trim($keys[1]); 
    $arr[$key] = $item; 
} 
print_r($arr); 

CodePade

+1

谢谢@NullPointer。 –

0
foreach($newStr as $key=>$value){ 
     echo $key; 
     echo $value; 
} 
+0

OP不想只回声(显示)他只想回声...检查[tpaksu](http://stackoverflow.com/a/13815039/1723893) –

0
<?php 
    $str = 
    "tel: (123) 123-4567 
    fax : (234) 127-1234 
    email : [email protected]"; 

$contacts = array(); 
$rows = explode("\n", $str); 
foreach($rows as $row) { 
    list($type, $val) = explode(':', $row); 
    $contacts[trim($type)] = trim($val); 
} 
var_export($contacts); 

返回

array (
    'tel' => '(123) 123-4567', 
    'fax' => '(234) 127-1234', 
    'email' => '[email protected]', 
) 
0

使用使preg_split与分隔符 “:” 和 “\ n” 个(换行符):

$newStr = preg_split("\n|:", $str); 
0
$str = 
    "tel: (123) 123-4567 
    fax : (234) 127-1234 
    email : [email protected]"; 

$array = array(); 
foreach (preg_split('~([\r]?[\n])~', $str) as $row) 
{ 
    $rowItems = explode(':', $row); 
    if (count($rowItems) === 2) 
     $array[trim($rowItems[0])] = trim($rowItems[1]); 
} 

您必须使用preg_split,因为每个系统上可能有不同的换行符。字符串也有可能是无效的,所以你应该处理(在foreach循环中的条件)

2

这是一个较短的方式与regular expressions

preg_match_all('/(\w+)\s*:\s*(.*)/', $str, $matches); 
$newStr = array_combine($matches[1], $matches[2]); 

print_r($newStr); 

结果:

Array 
(
    [tel] => (123) 123-4567 
    [fax] => (234) 127-1234 
    [email] => [email protected] 
) 

example here

但是这个例子假定的是,每个数据对是在一个单独的线路中提供的字符串中,并且“密钥”不包含空格。