Utku Dalmaz
Utku Dalmaz

Reputation: 10172

extracting a word starting with a specific letter from a string

I want to extract all words starting with @ in a string with php.

Which way is the best ?

EDIT: I dont want to fetch emails

Thanks

Upvotes: 1

Views: 3329

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

$matches = null;
preg_match_all('/(?!\b)(@\w+\b)/','This is the @string to @test.',$matches)

Using preg_match_all and taking advantage of a look-ahead for the start of a word ((?!\b)) and word delimiter (\b), you can achieve this easily. Broken down:

/           # beginning of pattern
  (?!\b)    # negative look-ahead for the start of a word
  (         # begin capturing
    @       # look for the @ symbol
    \w+     # match word characters (a-z, A-Z, 0-9 & _)
    \b      # match until end of the word
  )         # end capturing
/           # end of pattern

demo

Upvotes: 8

Related Questions