Reputation: 33684
I have the following code with regex trying to remove the hashtag from a string:
$text = "#jualan #jualanku #bag #bandung #jakarta #olshop #olshopindo #olshopindonesia #trusted #trustedseller #trustedolshop #tas #tasbagus #goodquality #premium #premiumquality #trixie #trixie bag #baju #kaos #spandex #bestseller #trixiewardrobe \nBella top\n\nSize s m l\n\nIdr 99.000\n\nLine: merlinehadiwijaya";
$newCaption = preg_replace('/#(?=[\w-]+)/', '', preg_replace('/(?:#[\w-]+\s*)+$/', '', $text));
however it only removes the '#' and not the whole hashtag. What am I doing wrong in my regex?
I wanted the result to be:
\nBella top\n\nSize s m l\n\nIdr 99.000\n\nLine: merlinehadiwijaya
Upvotes: 3
Views: 2716
Reputation: 70750
You are first using a Positive Lookahead assertion which only asserts that the specified characters follow the preceding pound sign, which is the reason only the pound sign is being removed from the input string. Secondly you are trying to use cascading preg_replace()
calls which is not necessary. You could simply do this in one call ...
$newCaption = preg_replace('/#\S+ */', '', $text);
Note: You have bag
without a preceding hashtag as well, so this will also be retained in the result.
Output
bag
Bella top
Size s m l
Idr 99.000
Line: merlinehadiwijaya
Upvotes: 4