Reputation: 973
In php if I capture a string
$string = 'gardens, countryside @teddy135'
how do I capture @username
from that string to a new variable in php username begins with @
preceded by a space and terminating in a space or the end of the string?
so I would end up with
$string = 'gardens, countryside'
$username ='@teddy135'
Upvotes: 0
Views: 41
Reputation: 1862
$regex = "/\s(@\S+)/";
$mystr = "gardens, countryside @teddy135 @xyz-12 and @abc.abc";
preg_match_all($regex, $mystr, $matches);
print_r($matches);
Upvotes: 0
Reputation: 87203
Use following regex
\s@(\w+)\b
\s
: Matches one space@
: Matches @
literally(\w+)
: Matches one or more alphanumeric characters including _
and put it in first capturing group\b
: Word boundaryCode:
$re = "/\\s@(\\w+)\\b/";
$str = "gardens, countryside @teddy135 @tushar and @abc";
preg_match_all($re, $str, $matches);
Upvotes: 2