1

I am trying to match an "ID" in a string, composed by some numbers (ranging from 1 digit to ~9 (the point is that it has got a variable length). The following code won't backreference my ID, I'm very new to PHP and I've tried google with no good answer.

<?php
$to = 'data-hovercard="/ajax/hovercard/user.php?id=100002781344760">Ae fj';

preg_match('/user.php?id=[\d]+\\"/', $to, $matches);

echo $matches[0];
?>

The whole point is to get the "10000278134476" in "/ajax/hovercard/user.php?id=100002781344760">". Any useful regexes?

ppp
  • 522
  • 3
  • 18
  • [Please do not use regex to parse HTML](http://stackoverflow.com/a/1732454/247893) – h2ooooooo Feb 16 '13 at 23:57
  • Sure don't look like HTML to me – James Feb 16 '13 at 23:59
  • @James It wouldn't make any sense to use a HTML data attribute in a string for something parsed through AJAX or somewhere where you haven't stripped it off. Of course I can't be sure, I just wanted to make sure that OP and others would know that you shouldn't. – h2ooooooo Feb 17 '13 at 00:01
  • First: lol nice zalgo text. Second: I just need to parse the id=. I can't even see Murphy's Law meddling in this because it's as basic as "1 == 1". – ppp Feb 17 '13 at 00:02
  • @user2079457 If you have no other elements on the page with any attribute, tag name, user string etc. containing `/user.php?id=123`, then sure, you'll be fine. :-) – h2ooooooo Feb 17 '13 at 00:04
  • Ĭ̘̰̞̪̖̱̞̺̘ͪ̉̓͑ͥ̚͘͜͞͞͡ͅ'̷̷̢̥̱͙̝̩̗̼̪̫̺̺͇͋̋̎̂̋ͤ̾̔̊ͨ̍ͫ̚͡ͅl͎̞͚̬̙̠͎͇̣̗͙̰̗͈̯̯̗̅̒̀͆ͥͣͩ̎ͭ̐̄ͤ͆ͦ̆͆̔ͬ͗̕͝l̛̑́ͮ̂̾̾҉̸̯̫̖̹̺́ ̵̧̫͚̼͎̬̲̄́̔̓͆̾̒̀ͫͭ͌̿̅ͣ̅͑́̚b̶̧̹̗̗͍͚̥͕̬̈ͫ̽͒̑̚͡ḙ̶̭̭͇͎̝̺̭̲͔̬̼̜̭͔̗͈̃̓ͩ̂͛ͫ̆͊̏ͮͧ̅ͭ̓̈́̌͠ ̢̩̳͚̯̹̪̹̞̜͔̙͉̣͕̱͛̃͗ͥͩ̽̇͐ͪ̔̔ͦ̀́͜͠ͅͅf̥̱̻̰̘̻̩͕̳̜̘͙̟̌̃ͭ̄̈́͐ͩͪͫ́ͦ̍̌ͭ̓̆ͥ́͜i̸̬͇̗̘͓̗̞͚͔͖̻̗͙̝̩̳͙̣̿ͨͪͪ̔͂̎ͤ̎ͧ̀ͅn̢̫͈͙̱̞͇͓̹̬̱̬̖͗ͥ͐ͨ͘e̵̺̥͈̻̥̞͙͍͕̣̭̬͈͗̒̿̓͋̕͜,̸̻̳̪͎̲͖͕̘͈͔ͯ͐̄ͯ̍̀̕ ̴̉ͩ̓͐ͫͦ̄͌͐̌́̕͞҉̲̖̼͖͈͎͈̮̤t̡̟̩̭́̒̓ͩ̃̓̇̉̎́͟͝h̢͕͖͈̺͈̫͗ͮ̓͋̄͒͆͌͝ã̢̠̳̬̼̝̇̐͒ͩͦ͂̇̃̎̌̉ͫ͂̉̚͞͡ͅn̡̧̊̃́͂ͬͣͪͧ̂͒͜҉͍̳̝̲͚̰̖͕̣̩͚̳̟͍̬̘k̴̡̢͇̭͇͙̟̗̝̫̦͇̯͇̦͕̈́ͮ̓̄̒̀ͪ̐ͧ̇̃̊̋̋ͨͨ͂͜͢ş̷̷͎̯͖̦̯͖͖̝̰̌̎ͮ͘͡.̷͕̭̩̼̰̮̰̭̦͍͙̝͎͔̱͖̦̓ͨ̑̿̐̑̇̾ͤ̐̈͒̊͛̌́́̕ͅ – ppp Feb 17 '13 at 00:07

1 Answers1

0

Adding ()s to mark groups should work, or if you want to make it more meaningful you can try named groups with (?<name>):

preg_match('/user.php?id=([\d]+)\\"/', $to, $matches);
//                       ^     ^
echo $matches[1]; // capture groups indexed from 1, 0 index is for the whole matched string

See the docs for more on the pattern sytnax.

complex857
  • 20,425
  • 6
  • 51
  • 54
  • It does not work for me. "PHP Notice: Undefined offset: 1 in test.php on line 7" – ppp Feb 16 '13 at 23:58
  • 1
    Your pattern is screwed up, it should be `/user.php\?id=(\d+)/` Escaping the ? and you dont need to worry about the end quote in fact it could screw up the regex if one url you parse has another parameter. – James Feb 17 '13 at 00:02