Skip to content

Instantly share code, notes, and snippets.

@summatix
Created December 16, 2014 20:44
Show Gist options
  • Save summatix/394606da99862caef8f6 to your computer and use it in GitHub Desktop.
Save summatix/394606da99862caef8f6 to your computer and use it in GitHub Desktop.
PHP: Remove hashtags from a caption
<?php
/**
* Removes hashtags from the given text. Hashtags at the end of the text are removed,
* and hashtags within the text are unhashed.
*
* E.g.
* Case 1: This is an example with lots of hashtags at the end #hash1 #hash2 #hash3 #hash4 #hash5
* Result: This is an example with lots of hashtags at the end
*
* Case 2: Look at this #great #food! #ilovehashtags #share #example
* Result: Look at this great food!
*
* @param string $caption The text to remove hashtags from
* @return string The given text with hashtags removed
*/
function remove_hashtags($caption)
{
// Get ready for some regex magic...
return
// Remove remaining hashes but keep the text inside the caption
trim(str_replace('#', '',
trim(preg_replace('/^(.+?)#\w+$/m', '${1}', // Edge case #hash1
trim(preg_replace('/^(.+?)#\w+ #\w+$/m', '${1}', // Edge case #hash1 #hash2
// Main case where there are at least three hashtags at the end of the string
trim(preg_replace('/^(.+?)#\w+ (#\w+ )+#\w+$/m', '${1}',
trim($caption)))))))));
}
@zlove
Copy link

zlove commented Oct 24, 2015

Works like a charm. Thanks Summatix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment