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
https://forums.phpfreaks.com/topic/251695-extract-part-of-a-string/
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);
?>

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);

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;  

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.