preg_match all words start with an @?

前端 未结 5 1808
栀梦
栀梦 2021-01-25 08:05

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

相关标签:
5条回答
  • 2021-01-25 08:57

    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
    
    0 讨论(0)
  • 2021-01-25 09:01

    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.

    0 讨论(0)
  • 2021-01-25 09:05

    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
    
    0 讨论(0)
  • 2021-01-25 09:09

    @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;
        }
    }
    
    0 讨论(0)
  • 2021-01-25 09:10

    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] == "@")
    
    0 讨论(0)
提交回复
热议问题