PHP Using RegEx to get substring of a string

PhpRegexParsingSubstring

Php Problem Overview


I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need.

I am parsing a web page and need to grab a numeric value from the string, the string is like this

producturl.php?id=736375493?=tm

I need to be able to obtain this part of the string:

736375493

Thanks Aaron

Php Solutions


Solution 1 - Php

$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);

This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

php.net/preg-match

Solution 2 - Php

<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>

Solution 3 - Php

$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);

Solution 4 - Php

Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.

There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

Code (Demo)

$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

736375493

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMonkeyBlueView Question on Stackoverflow
Solution 1 - PhpDavid FellsView Answer on Stackoverflow
Solution 2 - PhpanubhavaView Answer on Stackoverflow
Solution 3 - PhpslandauView Answer on Stackoverflow
Solution 4 - PhpmickmackusaView Answer on Stackoverflow