What is best practice to get
584ef6a14e69e
out of string /files/028ou2p5g/blogs/70cw99r5k/584ef6a14e69e-120.jpg
?
Assume all data is not constant. I need symbols after last slash and before minus sign.
What is best practice to get
584ef6a14e69e
out of string /files/028ou2p5g/blogs/70cw99r5k/584ef6a14e69e-120.jpg
?
Assume all data is not constant. I need symbols after last slash and before minus sign.
Use the proper tools so that there is no guesswork. This gets the filename without extension and then everything before the -
:
$string = '/files/028ou2p5g/blogs/70cw99r5k/584ef6a14e69e-120.jpg';
$result = strstr(pathinfo($string, PATHINFO_FILENAME), '-', true);
Or slightly shorter:
$result = strstr(basename($string), '-', true);
Assuming it will always be -120.jpg
and the part you want to get is composed of a-z and 0-9 characters, you may do as follow (using regex):
<?php
preg_match(
'/([a-z0-9]+)-120\.jpg$/',
'/files/028ou2p5g/blogs/70cw99r5k/584ef6a14e69e-120.jpg',
$matches
);
var_dump($matches[1]);
otherwise, if always a number:
<?php
preg_match(
'/([a-z0-9]+)-[0-9]+\.jpg$/',
'/files/028ou2p5g/blogs/70cw99r5k/584ef6a14e69e-120.jpg',
$matches
);
var_dump($matches[1]);
you may want to play more with regex in order to do something fitting more your needs (testing the length, case sensitivity, place in the string...)
<?php
$string = '/files/028ou2p5g/blogs/70cw99r5k/584ef6a14e69e-120.jpg';
$string = basename($string);
// remove all characters after and including '-' if it exists in string
$pos = strpos($string, '-');
if ($pos !== false)
$string = substr($string, 0, $pos);
echo $string; // outputs: 584ef6a14e69e
?>