-4

As i am new to regular expression i want to fetch exact number from string.I here paste code that i tried please tell me solution.In below code i can fetched number 4000 and 1 but i want only 4000 not 1 which is with 'a'

 $str = "4000+a1";
 preg_match_all('/[0-9]+/', $str, $matches);
 return $matches;
user7596840
  • 137
  • 15
  • Use `preg_match` and then use `$matches[0]`. Why `preg_match_all`??? It is matching all digits and returning an array of them. What do you need? – AbraCadaver Jan 03 '18 at 04:43
  • then you can try `preg_match_all('/[0-9]{4}/', $str, $matches);` – Ravi Sachaniya Jan 03 '18 at 04:45
  • 1
    my string can be "4000+a1+1000" in this case i want 4000 and 1000 – user7596840 Jan 03 '18 at 04:45
  • 2
    That's good info to have in the question, don't you think? – AbraCadaver Jan 03 '18 at 04:46
  • What's the pattern? They are 4 digits or what? – AbraCadaver Jan 03 '18 at 04:49
  • that can be any number – user7596840 Jan 03 '18 at 04:50
  • 1
    @AbraCadaver, no need to be furious. In the question, he stated **not 1 which is with 'a'**. You can guess/imply that he doesn't want the number together with a letter – Goma Jan 03 '18 at 04:56
  • 1
    @Erwin: Really? so `4000+a1+1000b` or `4000+a1+x1000` shouldn't capture the `1000`? That's your guess? Then please answer and edit your question until you are ready to hang yourself. :-) Especially given the comment _my string can be "4000+a1+1000" in this case i want 4000 and 1000_ it is very UNCLEAR what the OP wants. – AbraCadaver Jan 03 '18 at 05:01

2 Answers2

0

You can try with this pattern

$str = "4000+a1";
preg_match_all('/\b\d+\b/', $str, $matches);
return $matches;

\b - asserts position at a boundary
\d+ - matches a digit, one to unlimited times

Luffy
  • 1,028
  • 5
  • 13
-1

You could start at the beginning of the string by using the ^ symbol.

$str = "4000+a1";
preg_match_all('/^[0-9]+/', $str, $matches);
return $matches;
JasonB
  • 6,243
  • 2
  • 17
  • 27