0

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'

2
  • 1
    \s@(\w+)\b Commented Dec 18, 2015 at 6:20
  • @Tushar you should post this as answer with explanation Commented Dec 18, 2015 at 6:21

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

would that be like preg_match_all('\s@(\w+)\b',$string,$username);
@BarryHamilton I've added code too at the bottom of answer
cheers, I will accept when the window allows, you were very quick!
array(2) { [0]=> string(10) " @teddy135" [1]=> string(8) "teddy135" } when I dump $matches it has captured it twice once with @ and once without?
@BarryHamilton The one at index 1 is the first captured group, you can use $matches[1] to get the username, if you want @ symbol too, then use $matches[0]
0
$regex = "/\s(@\S+)/"; 
$mystr = "gardens, countryside @teddy135 @xyz-12 and @abc.abc"; 

preg_match_all($regex, $mystr, $matches);
print_r($matches);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.