Skip to content

Instantly share code, notes, and snippets.

@Simounet
Created January 29, 2014 13:08
Show Gist options
  • Save Simounet/8687564 to your computer and use it in GitHub Desktop.
Save Simounet/8687564 to your computer and use it in GitHub Desktop.
Get tags from a mixed string with or without quotes (grouped or not)
<?php
function getTags($tag_list) {
$matches = array();
// Get the words grouped between quotes (ex: "Manu Chao")
preg_match_all('~(["\'])([^"\']+)\1~', $tag_list, $quoted);
// Get the others
$unescaped = trim(str_replace($quoted[0], "", $tag_list));
$unescaped = preg_replace('/(\s)+/', ' ', $unescaped);
$matches = array_merge((array)$quoted[2], (array)explode( ' ', $unescaped ));
unset($quoted, $unescaped);
return count($matches) > 0 ? $matches : array();
}
$str = '"Philippe Katerine" "Willy Moon" Borderline "Yeah Yeah" "La Masheillaise 2" "Mighty Mike" bootleg';
$tag_list = getTags($str);
echo '<pre>' . print_r($tag_list, true) . '</pre>';
/* Result:
Array
(
[0] => Philippe Katerine
[1] => Willy Moon
[2] => Yeah Yeah
[3] => La Masheillaise 2
[4] => Mighty Mike
[5] => Borderline
[6] => bootleg
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment