MonkeyBlue
MonkeyBlue

Reputation: 2234

Get integer value from malformed query string

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

Upvotes: 80

Views: 134470

Answers (4)

mickmackusa
mickmackusa

Reputation: 47991

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

For completeness, there is another way to scan the formatted string and explicitly return an int-typed value. (Demo)

var_dump(
    sscanf($str, '%*[^?]?id=%d')[0]
);

The %*[^?] means: greedily match one or more non-question mark characters, but do not capture the substring. The remainder of the format parameter matches the literal sequence ?id=, then greedily captures one or more numbers. The returned value will be cast as an integer because of the %d placeholder.

Upvotes: 3

David Fells
David Fells

Reputation: 6798

$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

Upvotes: 106

anubhava
anubhava

Reputation: 785631

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

Upvotes: 27

slandau
slandau

Reputation: 24072

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

Upvotes: 6

Related Questions