1

Hello i have a problem with a regexp.

for example i have this text

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

and i want to get an array like this

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

)

with all data from the string , i tried this function.

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;

}

but the response is not correct

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

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

Any idea about this? .

3
  • 1
    or just explode it, shift, chunk by twos, foreach assignment to new container Commented Apr 7, 2016 at 1:24
  • 2
    I don't think using regex is the good way here. Commented Apr 7, 2016 at 1:25
  • Do you really want a multidimensional array or just a simple associative array? Commented Apr 7, 2016 at 1:54

2 Answers 2

3

NON - Regex

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

Using the string above, you can use this script to process it into the array that you wanted.

$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);

OUTPUT

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
        )
)
Sign up to request clarification or add additional context in comments.

Comments

0

try this:

$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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.