I see 3 ways (I’m not sure about which one has the best perfs, but I will bet on the last procedural way):
- Using the json_decode function, you will get an array from your string and then just iterate over it to get your data
- Using regexp, see an example here with pattern
/subdomain:(.*?),.*?comment:(.*?),/
-
Using a procedural function, like :
$subdomains = []; $comments = []; $subdomainLen = strlen('subdomain:'); $commentLen = strlen('comment:'); $str="{item_type:a,custom_domain:"google.com",subdomain:analytics,duration:324.33, id:2892928, comment:goahead,domain_verified:yes}, {item_type:b,custom_domain:"yahoo.com",subdomain:news,comment:awesome,domain_verified:no}, {item_type:c,custom_domain:"amazon.com",subdomain:aws,width:221,image_id:3233,height:13, comment:keep it up,domain_verified:no}, {item_type:d,custom_domain:"facebook.com",subdomain:m,slug:sure,domain_verified:yes}"; // While we found the 'subdomain' pattern while(($subdomainPos = strpos($str, 'subdomain'))) { // Removes all char that are behind 'subdomain' $str = substr($str, $subdomainPos + $subdomainLen); // Retrieves the subdomain str and push to array $subdomains[] = substr($str, 0, strpos($str, ',')); // If pattern 'comment' exists, do the same as before to extract the comment if($commentPos = strpos($str, 'comment')) { $str = substr($str, $commentPos + $commentLen); $comments[] = substr($str, 0, strpos($str, ',')); } }
solved Match strings starts and end with particular character in a String using PHP? [closed]