Leah Collins
Leah Collins

Reputation: 637

Preg replace to words with hash

I want to remove all username that start with # in a string. I tried this

preg_replace('/#/', '', 'blah blah blah #key blah blah');

But it removes only the #.

I appreciate any help.

Upvotes: 0

Views: 1361

Answers (3)

Prasanth Bendra
Prasanth Bendra

Reputation: 32740

Try this :

echo preg_replace('/#\w+/', '', 'blah blah blah #key blah blah');

output : blah blah blah blah blah

Upvotes: 1

Oto Shavadze
Oto Shavadze

Reputation: 42763

If your usernames not contain spaces, then this should work

preg_replace('/#[^\s]+/', '', 'blah blah blah #key blah blah');

Upvotes: 3

h2ooooooo
h2ooooooo

Reputation: 39532

/#[^\b]+/ should work fine.

Explanation of regex:

  • # A litteral # character
  • [^\b]+ Matches anything until a word boundary is hit
    • ^ means "not"
    • \b is a word boundary and will match any non-alphanumerical character (or end of string), and therefore supports "my string #username. Another string" to just match #username which is something that eg. [^\s]+ does not support. (it would match it with the period)
    • + means "repeated one or more times"

In code:

preg_replace('/#[^\b]+/', '', 'blah blah blah #key blah blah');

Upvotes: 3

Related Questions