Barry Hamilton
Barry Hamilton

Reputation: 973

php regexp how to capture substring to variable

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

Answers (2)

Mayur Koshti
Mayur Koshti

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

Tushar
Tushar

Reputation: 87203

Use following regex

\s@(\w+)\b

Regex101 Demo

  1. \s: Matches one space
  2. @: Matches @ literally
  3. (\w+): Matches one or more alphanumeric characters including _ and put it in first capturing group
  4. \b: Word boundary

Code:

$re = "/\\s@(\\w+)\\b/"; 
$str = "gardens, countryside @teddy135 @tushar and @abc"; 

preg_match_all($re, $str, $matches);

Upvotes: 2

Related Questions