使用PHP,如何转换此字符串:
$str = "Lorem ipsum dolor sit amet 00541000004UDewAAG consectetur adipiscing elit 00541000003WKoEAAW eiusmod tempor incididunt 00541000003WKmiAA";
进入这样的数组:
$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"],
];
“提及”类型始终具有以下格式:“00541000003WKoEAAW”,这是Salesforce ID,而其他所有内容都是常规文本..
感谢任何帮助。
答案 0 :(得分:0)
您可以使用爆炸功能http://php.net/manual/en/function.explode.php
$str = "Lorem ipsum dolor sit amet 00541000004UDewAAG consectetur adipiscing elit 00541000003WKoEAAW eiusmod tempor incididunt 00541000003WKmiAA";
$array = explode(' ', $str);
$generated = array();
$y = "";
for($x= 0; $x < sizeOf($array); $x++){
if (substr($array[$x], 0, 3) != '005') {
$y .= ' ' . $array[$x]; //CONCAT WORDS
} else {
$temp = array("type" => "Text", "text" => $y); //create the text array
$temp2 = array("type" => "Mention", "id" => $array[$x]); //create the id array
array_push($generated, $temp, $temp2); //then push it
$temp = array(); //make array null
$temp2 = array();
$y = null; //and null
}
}
print_r($generated);
答案 1 :(得分:0)
<?php
$str = "Lorem ipsum dolor sit amet 00541000004UDewAAG consectetur adipiscing elit 00541000003WKoEAAW eiusmod tempor incididunt 00541000003WKmiAA";
$startWith = '005';
$exploded = explode(' ', $str);
$result = [];
$lastIndex = 0;
foreach ($exploded as $index => $word) {
if (strpos($word, $startWith) === 0) {
$textExploded = array_filter(array_slice($exploded, $lastIndex, $index - $lastIndex));
$result = array_merge($result, [
['type' => 'Text', 'text' => implode(' ', $textExploded)],
['type' => 'Mention', 'id' => $word]
]);
if (isset($exploded[$index +1])) {
$lastIndex = $index + 1;
}
}
}
//var_dump($result);
答案 2 :(得分:0)
我不得不使用preg_split()+组合两个数组。这解决了文本被切断的问题 - 如果ID在字符串的开头等等。
$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);