Tutorial :preg_match all words start with an @?



Question:

i'm not very firm with regular Expressions, so i have to ask you:

How to find out with PHP if a string contains a word starting with @ ??

e.g. i have a string like "This is for @codeworxx" ???

I'm so sorry, but i have NO starting point for that :(

Hope you can help.

Thanks, Sascha


okay thanks for the results - but i did a mistake - how to implement in eregi_replace ???

$text = eregi_replace('/\B@[^\B]+/','<a href="\\1">\\1</a>', $text);  

does not work??!?

why? do i not have to enter the same expression as pattern?


Solution:1

Match anything with has some whitespace in front of a @ followed by something else than whitespace:

$ cat 1812901.php    <?php      echo preg_match("/\B@[^\B]+/", "This should @match it");      echo preg_match("/\B@[^\B]+/", "This should not@ match");      echo preg_match("/\B@[^\B]+/", "This should match nothing and return 0");      echo "\n";  ?>    $ php 1812901.php   100  


Solution:2

break your string up like this:

$string = 'simple sentence with five words';  $words = explode(' ', $string );  

Then you can loop trough the array and check if the first character of each word equals "@":

if ($stringInTheArray[0] == "@")  


Solution:3

Assuming you define a word a sequence of letters with no white spaces between them, then this should be a good starting point for you:

$subject = "This is for @codeworxx";  $pattern = '/\s*@(.+?)\s/';  preg_match($pattern, $subject, $matches);  print_r($matches);  

Explanation: \s*@(.+?)\s - look for anything starting with @, group all the following letters, numbers, and anything which is not a whitespace (space, tab, newline), till the closest whitespace.

See the output of the $matches array for accessing the inner groups and the regex results.


Solution:4

@OP, no need regex. Just PHP string methods

$mystr='This is for @codeworxx';  $str = explode(" ",$mystr);  foreach($str as $k=>$word){      if(substr($word,0,1)=="@"){          print $word;      }  }  


Solution:5

Just incase this is helpful to someone in the future

/((?<!\S)@\w+(?!\S))/  

This will match any word containing alphanumeric characters, starting with "@." It will not match words with "@" anywhere but the start of the word.

Matching cases:

@username  foo @username bar  foo @username1 bar @username2  

Failing cases:

foo@username  @username$  @@username  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »