{"created_at":"Sun Jun 11 07:50:06 +0000 2017","id":873809551614660608,"id_str":"873809551614660608", $s = ' {"created_at":"Sun Jun 11 07:50:06 +0000 2017","id":873809551614660608,"id_str":"873809551614660608", ';
วิธี
$string = '{"created_at":"Sun Jun 11 07:50:06 +0000 2017","id":873809551614660608,"id_str":"873809551614660608"'; echo $string.'<br>'."\n"; preg_match('#[\'|"]id[\'|"][\s]*:[\s]*(?<id>\d+)#i', $string, $matches); echo '<pre>'.print_r($matches, true).'</pre>'."\n";
จะได้
Array ( [0] => "id":873809551614660608 [id] => 873809551614660608 [1] => 873809551614660608 )
* id คลุมด้วย ” หรือ ‘ ก็ได้ (ใช้ [\’|”])
* [\s]*:[\s]* หมายถึง หลังและก่อน : มีหรือไม่มี space ก็ได้
* ?<id> คือระบุลงไปว่าถ้าเจอให้จับมันยัดใส่ array key “id”
* i ด้านท้าย pattern หมายถึงตัวใหญ่เล็กได้หมด
—
ถ้าเป็นแบบนี้ละ
[id] => 874536447386177536 [id_str] => 874536447386177536 [text] =>
วิธี
$string = '{"created_at":"Sun Jun 11 07:50:06 +0000 2017","id":873809551614660608,"id_str":"873809551614660608"'; preg_match_all('#[\'|"](\w+)[\'|"][\s]*:[\s]*["]?([a-zA-Z0-9\:\-_+\s]*)["]?#i', $string, $matches); echo '<pre>'.print_r($matches, true).'</pre>'."\n";
จะได้
Array ( [0] => Array ( [0] => "created_at":"Sun Jun 11 07:50:06 +0000 2017" [1] => "id":873809551614660608 [2] => "id_str":"873809551614660608" ) [1] => Array ( [0] => created_at [1] => id [2] => id_str ) [2] => Array ( [0] => Sun Jun 11 07:50:06 +0000 2017 [1] => 873809551614660608 [2] => 873809551614660608 ) )