php-regexHow to use PHP regex to match a hashtag?
Using PHP regex to match a hashtag is a simple process. The following example code block will match a hashtag in a string:
$string = 'This is a #hashtag';
preg_match('/#([a-zA-Z0-9_]+)/', $string, $matches);
The output of the example code will be:
Array
(
[0] => #hashtag
[1] => hashtag
)
Code explanation
-
$string = 'This is a #hashtag';
: This is the string that contains the hashtag. -
preg_match('/#([a-zA-Z0-9_]+)/', $string, $matches);
: This is the regular expression used to match the hashtag. The#
symbol is used to match the hashtag, and the([a-zA-Z0-9_]+)
part is used to match the characters in the hashtag. -
$matches
: This is the array that will contain the matches from the regular expression.
Helpful links
More of Php Regex
- How to match a single quote in PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match special characters?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match a year?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match an XML tag?
- How to use PHP regex to match UTF8?
See more codes...