Reputation: 33684
I have the following regex:
preg_replace('/#(?=[\w-]+)/', '', preg_replace('/(?:#[\w-]+\s*)+$/', '', $stringText)
to basically replace/remove hashtags with empty string.
However it doesn't work for the following:
#jualbaju #blouse #jualmurah #bajumurah #jakarta #jualbajumurah #bajulucu #korea #dress #jualdress #murahmeriah #jualeceran #jualdressmurah #setelanmurah #jualsetelanmurah #bajupink #pink #jualshortdress #atasanmurah #bajukorea #bajukoreamurah #onlineshopindo #olshop #bajukoreamurah\n#jualbajukoreamurah #jualbajumurmer #dresskorea\n\nMinat hubungi cp di bio :) Line : shaneee22
Why is this?
Upvotes: 1
Views: 9973
Reputation: 786359
This should work for you:
$re = '/#\w+\s*/';
$result = preg_replace($re, '', $input);
EDIT: Use this regex if you don't want to remove new line characters from your input:
$re = '/#\w+\h*/';
Upvotes: 8
Reputation: 515
I would like to way in to this topic. I tried first two option none of them worked, it return empty string. Below code works for me and i think it is much simpler.
$re = '/#*/';
$result = preg_replace($re, '', $input);
Upvotes: -1
Reputation: 11
I'm not sure if you want to remove just the "#" or the name with it.
$string = "#jualbaju #blouse #jualmurah #bajumurah #jakarta #jualbajumurah #bajulucu #korea #dress #jualdress #murahmeriah #jualeceran #jualdressmurah #setelanmurah #jualsetelanmurah #bajupink #pink #jualshortdress #atasanmurah #bajukorea #bajukoreamurah #onlineshopindo #olshop #bajukoreamurah\n#jualbajukoreamurah #jualbajumurmer #dresskorea\n\nMinat hubungi cp di bio :) Line : shaneee22";
//Just the '#' removed
$noHashTag = str_replace('#', '', $string);
//The name too
$noHashTag = preg_replace('/#([\w-]+)/i', '', $string);
Upvotes: -1
Reputation: 41848
This is what you're looking for:
$replaced = preg_replace('~#[\w-]+~', '', $yourstring);
See the regex demo.
Explanation
#
matches the hash[\w-]+
matches one or more word chars or hyphensWhat was wrong?
preg_replace
didn't replace anything, because it couldn't find a series of hash tags followed by the end of the string (the $
anchor)preg_replace
only replaced the hashes, because what followed the hash was only a lookahead (?=[\w-]+)
, which doesn't consume charactersUpvotes: 1