PHP Using RegEx to get substring of a string

2019-02-02 19:46发布

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

3条回答
一夜七次
2楼-- · 2019-02-02 20:17
$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-02 20:19
<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>
查看更多
Viruses.
4楼-- · 2019-02-02 20:26
$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

查看更多
登录 后发表回答