phparrayssalesforcesalesforce-chatter

How to convert a string into a specific array


Using PHP, how do I convert this string:

$str = "Lorem ipsum dolor sit amet 00541000004UDewAAG consectetur adipiscing elit 00541000003WKoEAAW  eiusmod tempor incididunt 00541000003WKmiAA";

Into an array like this:

$messageSegments = [
 ["type" => "Text", "text" => "Lorem ipsum dolor sit amet "], 
 ["type" => "Mention", "id" => "00541000004UDewAAG"], 
 ["type" => "Text", "text" => "consectetur adipiscing elit"], 
 ["type" => "Mention", "id" => "00541000003WKoEAAW"], 
 ["type" => "Text", "text" => "eiusmod tempor incididunt"], 
 ["type" => "Mention", "id" => "00541000003WKmiAA"], 
];

The type "Mention" always has this format: "00541000003WKoEAAW" which is a Salesforce ID while everything else is regular text..

Any help is appreciated.


Solution

  • I had to use preg_split() + combining two arrays. This solves the issue of text getting chopped off - if the ID is in the beginning of the string, etc.

        $ids = [];
        $words = [];
        $final = [];
    
        $pattern = '/005[a-zA-Z|0-9]{15}/'; 
        $exploded = explode(' ', $text); 
    
        //get all the mention ids from new text
        foreach ($exploded as $index => $word) {
            if(preg_match($pattern, $exploded[$index])){
                //replace period or comma
                $id = str_replace(',','',str_replace('.','',$exploded[$index])); 
                array_push($ids,$id);
            }
        } 
        //get words array
        $words = preg_split($pattern, $text,-1, PREG_SPLIT_NO_EMPTY); 
    
        //find which is first: id or words
        $isIdFirst = preg_match('/^005/', $text); //if str starts with 005
    
        if($isIdFirst){
            for($x=0; $x < count($ids); $x++) {  
               array_push($final, ['type'=>'Mention','id'=>$ids[$x]]);
               if(isset($words[$x])){
                    array_push($final, ['type'=>'Text', 'text'=>$words[$x]]);
               }
            }
        }else{
            for($x=0; $x < count($words); $x++) {  
                array_push($final, ['type'=>'Text', 'text'=>$words[$x]]);
                if(isset($ids[$x])){
                    array_push($final, ['type'=>'Mention','id'=>$ids[$x]]);
                }
             }
        }  
        var_dump($final);