• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 188
  • Last Modified:

Parsing a string that changes in size

If I have a URL that looks like this:

http://www.abcdefghijklm.com/product-cat/some-kind-of-product/ID-515-M-MAR.htm

And I want to return just the 515 value, how can I do that?  I tried a combination of parse_url and substr, but my problem is that the numeric value (as well as the path) can vary in size and value.

Thanks.
0
jjfbuy
Asked:
jjfbuy
1 Solution
 
dr_dedoCommented:
<?
$str= "http://www.abcdefghijklm.com/product-cat/some-kind-of-product/ID-515-M-MAR.htm";
$str=substr($str,strrpos($str,'/')+1);
$str = preg_replace('/[^\d\/]/','',$str);
echo $str;
?>

this code will isolate the file (any thing after the last / ) and then return only the number part of it
0
 
RoonaanCommented:
Like dr_dedo, put without the substr:

$url= "http://www.abcdefghijklm.com/product-cat/some-kind-of-product/ID-515-M-MAR.htm";
$filename = basename($url);
$number  = preg_replace('/\D/', '', $filename);

-r-
0
 
aminerdCommented:
The provided solutions will return 1) any digits after the last '/', or, 2) any digits in the entire URL. This may or may not be what you need. In particular, Roonaan's solution will be susceptible to any digits that may exist in the site name, "product-cat", or "some-kind-of-product".

There are a number of ways to match what you need, differing with the URL specifications: what changes, what remains the same, what kind of characters the product category or name will contain, etc.

Assuming...

$url = 'http://www.abcdefghijklm.com/product-cat/some-kind-of-product/ID-515-M-MAR.htm';

If you just want to match any digit following the phrase '/ID-', you could do:

$number = (preg_match('/\/ID-(\d+)/', $url, $m) ? $m[1] : FALSE);

Getting a little more specific, this matches /ID-[digits]-*.htm, occuring at the end of the URL:

$number = (preg_match('/\/ID-(\d+)-.+?\.htm$/', $url, $m) ? $m[1] : FALSE);

Etc., etc.
0
 
RoonaanCommented:
Hi,

Aminerd provided the most complete solution. Both dr_dedo's and mine are inaccurate.

-r-
0
 
hujiCommented:
Thanks a lot for your notification Roonan. I really appreciate your taking time and commenting on my decision. I will make a correction to my desicion in the next pass.
Best regards,
Huji
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now