Jump to content

extract part of a string


php_begins

Recommended Posts

Hi i need help with some string manipulation and extraction..

http://www.test.com/forums/attachment/f39/745d1267084199-official-ar-m16-m4-picture-thread-dsc00005.jpg

 

I need to extract an id from the above path dynamically.

I need to extract the digits before the alphabet d after the second last  path f39/

In the above case the number extracted would be 745.

Can someone please help me out with it?

Link to comment
Share on other sites

<?PHP

  //### Only get what is needed of the actualy URL
  $string   = 'http://www.test.com/forums/attachment/f39/745d1267084199-official-ar-m16-m4-picture-thread-dsc00005.jpg';
  $string   = end(explode('/',$string));

  //### Preg_match the "d" to return numbers only
  preg_match("/[\d]{1,}/", $string,$match);

  print_r($match);
?>

Link to comment
Share on other sites

You could use pathinfo to get the basename and run the preg_match on that:

 

$url = "http://www.test.com/forums/attachment/f39/745d1267084199-official-ar-m16-m4-picture-thread-dsc00005.jpg";
$getpath = pathinfo($url);
$basename = $getpath[basename];
$getpath = preg_match("/^[\d]+/", $basename, $match);

Link to comment
Share on other sites

thanks a lot...another useful solution i found was this:

 

$str = 'http://www.test.com/forums/attachment/f39/6066d1267084199-official-ar-m16-m4-picture-thread-dsc00005.jpg';
$filename = pathinfo($str, PATHINFO_FILENAME);
$part = substr($filename, 0, strpos($filename, 'd') - strlen($filename));
print $part;  

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.