Very simple, I need to match the #
symbol using a regex. I'm working on a hashtag detector.
I've tried searching in google and in stack overflow. One related post is here, but since he wanted to remove the # symbol from the string he didn't use regex.
I've tried the regexes /\b\#\w\w+/
, and /\b#\w\w+/
and they don't work and if I remove the #
, it detects the word.
# does not have any special meaning in a regex, unless you use it as the delimiter. So just put it straight in and it should work. Note that \b detects a word boundary, and in #abc , the word boundary is after the # and before the abc . Therefore, you need to use the \b is superfluous and you just need #\w\w+ .
With the comment on the earlier answer, you want to avoid matching x#x
.
In that case, your don't need \b
but \B
:
\B#(\w\w+)
(if you really need two-or-more word characters after the #).
The \B
means NON-word-boundary, and since #
is not a word character, this matches exactly if the previous character is not a word character.
#
does not have any special meaning in a regex, unless you use it as the delimiter. So just put it straight in and it should work.
Note that \b
detects a word boundary, and in #abc
, the word boundary is after the #
and before the abc
. Therefore, you need to use the \b
is superfluous and you just need #\w\w+
.
You don't need to escape it (it's probably the \b
that's throwing it off):
if (preg_match('/^\w+#(\w+)/', 'abc#def', $matches)) {
print_r($matches);
}
/* output of $matches:
Array
(
[0] => abc#def
[1] => def
)
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With