-1

Possible Duplicate:
Extract numbers from a string

I am using preg_match() to extract a number from a string.
Example string is: advent_id ----------- 3163 (1 row), I need to extract the number followed by the hyphens and not the number of rows. What is the correct way of writing a regex for it?
I tried preg_match('/^advent_id\s------------\s(.*)\s\(/', $cn, $matches); where $cn has that source string, but it did not work. Note that the number could have any number of digits.

Community
  • 1
  • 1
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
  • 1
    What do you mean by "it did not work"? Error? Wrong result? – Martin Ender Oct 01 '12 at 15:33
  • Your regex is a bit strange, in that on the one hand it requires a very specific format -- exact number of hyphens, etc. -- while on the other it's very loose -- using `\s` instead of a space, using `.*` instead of `\d+`, etc. – ruakh Oct 01 '12 at 15:37
  • @m.buettner it did not match anything. Well, '/\d+/' worked for me, thanks! – Rahul Desai Oct 01 '12 at 15:55

4 Answers4

2

Just extract the first integer in the row.

$x = 'advent_id ----------- 3163 (1 row)';
preg_match('/\d+/', $x, $m);
echo "$m[0]\n";

Produces:

3163

edit

as you can see, the default behaviour of preg_match() is to match the first occurrence, then stop. It's different of preg_match_all()

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

Code:

$s = 'advent_id ----------- 3163 (1 row)';
preg_match('~-+ (\d+)~', $s, $m);
print_r($m);

will output:

Array
(
    [0] => ----------- 3163
    [1] => 3163
)
Glavić
  • 42,781
  • 13
  • 77
  • 107
0

You were close. Your main problem was your .* was matching any character so you had to make your regular expression complicated to make sure it only was grabbing numbers. By changing that part to [0-9]* it will only match numbers and will make your regex simpler.

$cn = 'advent_id ----------- 3163 (1 row)';
preg_match('/^advent_id -* ([0-9]*)/', $cn, $matches);
print_r($matches[1]);
Aust
  • 11,552
  • 13
  • 44
  • 74
0

You can try

$string = "advent_id ----------- 3163 (1 row)" ;
$matches = array();
preg_match('/\d+/', $string, $matches);
print($matches[0]);

Output

 3163
Baba
  • 94,024
  • 28
  • 166
  • 217