PHP Using RegEx to get substring of a string

Posted on

PHP Using RegEx to get substring of a string – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and regex . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about PHP Using RegEx to get substring of a 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


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


Thanks Aaron

Solution :

$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.

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

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

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=Kd+~', $str, $out) ? $out[0] : 'no match';



Leave a Reply

Your email address will not be published. Required fields are marked *