adit
adit

Reputation: 33684

removing hashtags from a string

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

Answers (4)

anubhava
anubhava

Reputation: 786359

This should work for you:

$re = '/#\w+\s*/';
$result = preg_replace($re, '', $input);

Online Demo

EDIT: Use this regex if you don't want to remove new line characters from your input:

$re = '/#\w+\h*/';

Upvotes: 8

James Norman
James Norman

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

Mr.Hunt
Mr.Hunt

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

zx81
zx81

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 hyphens
  • we replace with the empty string

What was wrong?

  • the first 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)
  • the second preg_replace only replaced the hashes, because what followed the hash was only a lookahead (?=[\w-]+), which doesn't consume characters

Upvotes: 1

Related Questions