I accept string contains hashtags. Then I extract hashtags from string and unique them. So I have string and array of hashtags.
Before I post it I want to check for existance hashtags in database and create not existing tags, and then link all my tags to my new post.
function getHashtags($string) {
preg_match_all('/#(\w+)/', $string, $matches);
foreach ($matches[1] as $match) {
$keywords[] = $match;
}
return array_unique($keywords);
}
function getTagLinks($postContent, $collectionName) {
return array_map(function($tag) {
$collectionName = 'postTags';
$link = cockpit('collections')->findOne($collectionName, [
'title' => $tag,
]);
if (empty($link)) {
$link = cockpit('collections')->save($collectionName, ['title' => $tag] );
}
return [
'_id' => $link['_id'],
'link' => $collectionName,
'display' => $link['title'],
];
}, getHashtags($postContent));
}
It is simple to iterate through my tags, find if item exist, get link to it otherwise create it and get link. But this method is overthinking and cause a lot of requests. Can you suggest more native way?