How to match a pound (#) symbol in a regex in php (for hashtags)
#
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
)
*/