Match error with regular expressions in preg_match_all

0

The problem is that making a match of each occurrence of a character regex of the string returns everything well, but the first result always lacks the last character.

$string = "@user#12458 y @user2#12345 son dos apariciones";
preg_match_all('/\@(.*?)\#([0-9]*5)/i', $string, $mentions, PREG_SET_ORDER);
foreach ($mentions as $user){
    $x = $user[1];
    $x = $user[2];
    $getUser = $connection->prepare("SELECT id FROM x WHERE x =:x AND x =:x");
    $getUser->bindParam("x", $x);
    $getUser->bindParam("x", $x);
    $getUser->execute();
    $userId = $getUser->fetch();
    if ($userId>0) {
        echo "hay";
    }else{
        echo "no hay";
    }
}

The code above has a pregmatchall function with the irregular expression that is supposed to find everything that has a @, letters, # and numbers , I'm new in this of the regex so I had to check if it was ok and they told me that it is, but I do not know why when doing $user[1] of the first result, it returns "1245", leaving aside 8 which is the last character, but in the second result and $user[1] returns the complete number.

I tried editing the *5 by * and there are no problems, but also loses the joke on the function, because I only want 5 characters after 5, this only happens to me in php , it does not happen to me in js .

    
asked by Esteban Fernández 30.07.2018 в 20:31
source

1 answer

1

Your problem is in regex , it should be the following \@(.*?)\#([0-9]{5})/ .

The reason for the error is the following:

  

{5} Indicates that the result of the token above must   match the specified amount, in this case exactly 5 .

     

*5 Indicates that any amount of token previous (0 or more) and that must   match 5 at the end

    
answered by 30.07.2018 / 20:55
source