Search code examples
phpregexnumberspreg-match-alltext-extraction

Get numbers that immediately follow @ symbol in string


Imagine I have a textarea with the following value.

@3115
Hello this is a test post.

@115
Test quote

I'm trying to find a way in PHP using regex that will get the numeric value that comes after the '@' symbol even if there's multiple symbols.

I imagine storing the values that are returned from the regex into an array is what I'm looking for.


Solution

  • (Using a preg_match_all function as an example, but the function doesn't matter, the Regex within does:)

      $inputString = "@3115
            Hello this is a test post.
            @115
           Test quote";
      preg_match_all("/@(\d+)/",$inputString,$output);
      //$output[1] = "3115";      
      //$output[2] = "115";
    

    This will find a @ character, and then find \d which is any numerical value, and then + means to catch [the numerical value] one or more times. the () makes this a capture group so will only return the number found and not the @ preceeding it.