Reputation: 637
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
Reputation: 32740
Try this :
echo preg_replace('/#\w+/', '', 'blah blah blah #key blah blah');
output : blah blah blah blah blah
Upvotes: 1
Reputation: 42763
If your usernames not contain spaces, then this should work
preg_replace('/#[^\s]+/', '', 'blah blah blah #key blah blah');
Upvotes: 3
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