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.
-
If the string is always in that form, this is a fine way of doing ths. If the string is ever different, regex may be a better option of the length of the numbers is always the same.GrumpyCrouton– GrumpyCrouton2018年12月18日 13:42:03 +00:00Commented Dec 18, 2018 at 13:42
-
1You could use a regex if you really want to, but if what you have works for you, why worry.Jonnix– Jonnix2018年12月18日 13:42:08 +00:00Commented Dec 18, 2018 at 13:42
-
yes...always same lenght...Muhammad Hashir Anwaar– Muhammad Hashir Anwaar2018年12月18日 13:42:56 +00:00Commented Dec 18, 2018 at 13:42
-
@JonStirling, I am not much fimilar with regexMuhammad Hashir Anwaar– Muhammad Hashir Anwaar2018年12月18日 13:44:04 +00:00Commented Dec 18, 2018 at 13:44
-
@MuhammadHashirAnwaar Then stick with what you know?Jonnix– Jonnix2018年12月18日 13:44:54 +00:00Commented Dec 18, 2018 at 13:44
4 Answers 4
echo basename($image['img_link'], '.jpg');
an alternative if you have different file extensions:
echo pathinfo ( $image['img_link'] , PATHINFO_FILENAME );
10 Comments
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].
2 Comments
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');
1 Comment
You could use Regex
This pattern would work:
(\d{6}-\d{5}-\d{4})
Breakdown:
\dmeans "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