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 l
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
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.
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
@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;
}
}
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] == "@")