-3

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Tony
  • 351
  • 3
  • 19
  • @Martin yes it will always be the number after the @ symbol – Tony May 23 '17 at 16:16
  • Actually can you clarify if you want *all* the values or just the first? I assumed you wanted all of them, but rereading your post it's ambiguous? – Martin May 23 '17 at 16:25

3 Answers3

3

Try this:

$str = <<<EOF
@3115
Hello this is a test post.

@115
Test quote
EOF;

preg_match_all('/@(\d+)/', $str, $matches);
var_dump($matches[1]); // Returns an array like ['3115', '115']

The preg_match_all function gets all the occurrences of the regex in the input string and returns the capture group.

Regex breakdown

/@(\d+)/

  • @ matches the character literally.
  • ( starts a capture group.
  • \d matches a digit (equal to [0-9]).
  • + means the digit can be repeated one or more times.
  • ) ends the capture group.
Ethan
  • 4,295
  • 4
  • 25
  • 44
2

(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.

Martin
  • 22,212
  • 11
  • 70
  • 132
0

Match the @, forget it with \K, then match one or more digits as the fullstring match.

Code: (Demo)

$str = <<<TEXT
@3115
Hello this is a test post.

@115
Test quote
TEXT;

preg_match_all('/@\K\d+/', $str, $matches);
var_export($matches[0]);

Output:

array (
  0 => '3115',
  1 => '115',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136