Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

producturl.php?id=736375493?=tm

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

736375493

Thanks Aaron

like image 661
MonkeyBlue Avatar asked May 09 '11 19:05

MonkeyBlue


People also ask

How do I match a string in PHP?

You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2 ; returns > 0 if str1 is greater than str2 , and 0 if they are equal.

What is Preg_match_all in PHP?

The preg_match_all() function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found.

What is PHP regex?

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.


3 Answers

$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

like image 185
David Fells Avatar answered Sep 20 '22 22:09

David Fells


<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>
like image 36
anubhava Avatar answered Sep 22 '22 22:09

anubhava


$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);
like image 36
slandau Avatar answered Sep 20 '22 22:09

slandau