public static function parse($terms, $term_class = '\\Habari\\Term', $vocabulary = null)
{
if (is_string($terms)) {
if ('' === $terms) {
return new Terms();
}
$terms = trim(MultiByte::str_replace('"', '"', $terms));
// dirrty ;)
$rez = array('\\"' => ':__unlikely_quote__:', '\\\'' => ':__unlikely_apos__:');
$zer = array(':__unlikely_quote__:' => '"', ':__unlikely_apos__:' => "'");
// escape
$tagstr = str_replace(array_keys($rez), $rez, $terms);
// match-o-matic
preg_match_all('/((("|((?<= )|^)\')\\S([^\\3]*?)\\3((?=[\\W])|$))|[^,])+/u', $tagstr, $matches);
// cleanup
$terms = array_map('trim', $matches[0]);
$terms = preg_replace(array_fill(0, count($terms), '/^(["\'])(((?!").)+)(\\1)$/'), '$2', $terms);
// unescape
$terms = str_replace(array_keys($zer), $zer, $terms);
// hooray
}
if (is_array($terms)) {
if ($vocabulary instanceof Vocabulary) {
foreach ($terms as $k => $term) {
if ($saved_term = $vocabulary->get_term($term, $term_class)) {
$terms[$k] = $saved_term;
} else {
$terms[$k] = new $term_class($term);
}
}
} else {
array_walk($terms, function (&$tag) use($term_class) {
$tag = new $term_class($tag);
});
}
return new Terms($terms);
}
return new Terms();
}