regex - By using PHP preg_match, how to get specific substring from string

382

I would like to get substring:

myPhotoName

from the below string:

path/myPhotoName_20170818_111453.jpg

usingPHPpreg_match function.

Please may somebody help me?

Thank you.

273

Answer

Solution:

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 /

https://3v4l.org/9oTuj

Performance of regex:
enter image description here


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;

https://3v4l.org/d411c

Performnce of substring:
enter image description here

My conclusion
Regex is not suitable for this type of job as it's way to slow for such a simple substring pattern.

125

Answer

Solution:

Do like this:

<?php
$arr = "path/myPhotoName_20170818_111453.jpg";
$res = explode('_',explode('/',$arr)[1])[0];
print_r($res);
?>

Use explode function in place of preg_match for easily get your expected output. And using preg_match, do like this:

<?php
$img = "path/myPhotoName_20170818_111453.jpg";
preg_match("/path\/(.+)\_[0-9]*\_[0-9]*\.jpg/", $img, $folder);
print_r($folder[1]);
?>

People are also looking for solutions to the problem: javascript - The sessions only store data for a second before being changed the last sessions value

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.