0

I have seen two similar questions on SO here & here but still stuck...

I have a string of filepath like catalog/reviews/249532-20691-5369.jpg and i want to get numbers only like 249532-20691-5369.

I am using the following approach:

$id1 = explode('/', $image['img_link']);
$id2 = explode('.', $id1[2]);
echo $id2;  //output 249532-20691-5369 

Is there any best approach to do this task in controller.

4 Answers4

7

https://ideone.com/XGwrTc

echo basename($image['img_link'], '.jpg');

an alternative if you have different file extensions:

echo pathinfo ( $image['img_link'] ,  PATHINFO_FILENAME );
Alex
  • 16,739
  • 1
  • 28
  • 51
1

In your case, you could use a simple regular expression.

([^\/]+)\.jpg$

And in php this would look like this

preg_match('/([^\/]+)\.jpg$/', $image['img_link'], $m);
echo $m[1];

If you need it for any extension, you could use this

([^\/]+)\.[^\.]+$

So how does this work:

We start from the right, so we add an anchor to the line ending $. From there on, we want the extension, which is practically everything expect a point [^\.]+. Whats left is the file name, which is everything from the point until you reach the slash [^\/]+. This part is also enclosed in a capturing group () to access it in the end with $m[1].

Philipp
  • 15,377
  • 4
  • 35
  • 52
0

explode returns an array, so you need to access the first element:

$ids = explode('/', $image['img_link'];
$id2 = explode('.', end($ids));

echo $id2[0];

Alternatively, you can just use basename() instead of the first explode() (assuming you always have .jpg extension):

echo basename($image['img_link'], '.jpg');
BenM
  • 52,573
  • 26
  • 113
  • 168
0

You could use Regex

This pattern would work:

(\d{6}-\d{5}-\d{4})

Breakdown:

  • \d means "Any Digit"
  • {#} means a count of # values, and of course the dashes between the numbers.
  • Wrap the whole thing with parenthesis to capture the whole result

Code:

$string = "catalog/reviews/249532-20691-5369.jpg";

preg_match('(\d{6}-\d{5}-\d{4})', $string, $result);
echo $result[0];

Output:

249532-20691-5369
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71