Soundcloud's API returns a string of tags for each track like so:
Pop Rock "Soft Pop" "Soft Rock" "Easy Listening" Jazz
where the string contains a list of tags seperated by spaces. Multiword tags are quoted in doublequotes.
At first, I was using something like
$tracktags = 'Pop Rock "Soft Pop" "Soft Rock" "Easy Listening" Jazz';
if(strpos($tracktags, "Soft Rock") !== false) {
//we found a match
}
To find all songs that are Soft Rock
.
This becomes cumbersome when I am trying to narrow down tracks that include this 1 term when some of these terms include words being used in other tags.
So, for example if that tag I was looking for was Pop
, using this method I get songs that are tagged Soft Pop
, Country Pop
, Pop ballads
, and so on, because using strpos()
just finds that part of the string . That's not the result I am hoping for; in this instance I just want to get songs that are tagged Pop
.
I am thinking I need to separate this string into an array and then cycle through the array to make sure each value is implicitly identical to the tag I am searching for... but I'm not sure how I would do that. I guess split()
by the quotations, then split()
the remaining by spaces?
Is there a PHP function that can compare both the string and length of the string, I guess, to ensure it is identical to my searching term?
Try splitting into an array using str_getcsv()
with a space as the delimiter. It will use the quotes as enclosures by default and will ignore the space inside the quotes. Then just use in_array()
:
$tracktags = str_getcsv($tracktags, ' ');
if(in_array('Pop', $tracktags)) {
//we found a match
}
To see what's there:
print_r($tracktags);