【问题标题】:get array of string php regex获取字符串 php 正则表达式的数组
【发布时间】:2016-04-07 01:18:44
【问题描述】:

您好,我的正则表达式有问题。

例如我有这个文本

$textMessage = "|nif|<00/00/03364301P>|lat|<not set>|long|<not set>|deviceId|<1F26DE6896ADC816-001346E604E7>|messageId|<70154>";

我想得到一个这样的数组

$data = array(
array("nif" => "00/00/03364301P"),
array("lat" => "not set") // etc

)

使用字符串中的所有数据,我尝试了此功能。

function getArrayDataSMS($textMessage){
  $regexType = '/\|([a-zA-Z]+)\||<[\d]+>/';
  $rowValueData = preg_match_all($regexType, $textMessage, $matches,   PREG_SET_ORDER);

foreach ($matches as $key => $match) {
  $arrayData[trim($match[1])] = trim($match[2]);
}
return $arrayData;

}

但响应不正确

array(2) {
 [0]=>
 string(5) "|nif|"
  [1]=>
  string(3) "nif"
  }

 array(3) {
   [0]=>
     string(6) "<4545>"
   [1]=>
     string(0) ""
   [2]=>
     string(4) "4545"
  }

对此有任何想法吗? .

【问题讨论】:

  • 或者只是将其分解、移位、逐块、foreach 分配到新容器
  • 我不认为在这里使用正则表达式是个好方法。
  • 你真的想要一个多维数组还是一个简单的关联数组?

标签: php arrays regex string


【解决方案1】:

非 - 正则表达式

$textMessage = "|nif||lat||long||deviceId||messageId|";

使用上面的字符串,你可以使用这个脚本将它处理成你想要的数组。

$array = explode("|",$textMessage);
var_dump($array);

$data = array();

//Start with 1 since $array[0] is '';
//Assumed first and last characters <> are present and need to be removed
//Feel free to modify as needed

for($i = 1; $i < count($array); $i+=2) {
     $data[] = array($array[$i] => substr($array[$i+1], 1, -1));
}
echo "<pre>";
print_r($data);

输出

Array (
    [0] => Array (
            [nif] => 00/00/03364301P
        )

    [1] => Array (
            [lat] => not set
        )

    [2] => Array (
            [long] => not set
        )

    [3] => Array (
            [deviceId] => 1F26DE6896ADC816-001346E604E7
        )

    [4] => Array (
            [messageId] => 70154
        )
)

【讨论】:

    【解决方案2】:

    试试这个:

    $text = "|nif|<00/00/03364301P>|lat|<not set>|long|<not set>|deviceId|<1F26DE6896ADC816-001346E604E7>|messageId|<70154>";
    preg_match_all("/\|(\w+?)\|\<(.+?)>/",$text,$a);
    $result = array_combine($a[1],$a[2]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      相关资源
      最近更新 更多