I would like to get substring:
myPhotoName
from the below string:
path/myPhotoName_20170818_111453.jpg
using PHP
preg_match
function.
Please may somebody help me?
Thank you.
Preg_match from / to _.
$str = "blur/blur/myPhotoName_20170818_111453.jpg";
Preg_match("/.*\/(.*?)_.*(\..*)/", $str, $match);
Echo $match[1] . $match[2];
I use .*?
to match anything between the slash and underscore lazy to make sure it doesn't match all the way to the last underscore.
Edited to make greedy match anything before the /
Since it's such a simple pattern you can also use normal substr with strrpos.
Edited to use strrpos to get the last /
$str = "blur/blur/myPhotoName_20170818_111453.jpg";
$pos = strrpos($str, "/")+1; // position of /
$str = substr($str, $pos, strpos($str, "_")-$pos) . substr($str, strpos($str, "."));
// ^^ substring from pos to underscore and add extension
Echo $str;
My conclusion
Regex is not suitable for this type of job as it's way to slow for such a simple substring pattern.