[英]By using PHP preg_match, how to get specific substring from string
I would like to get substring: 我想得到子字符串:
myPhotoName
from the below string: 从下面的字符串:
path/myPhotoName_20170818_111453.jpg
using PHP
preg_match
function. 使用PHP
preg_match
函数。
Please may somebody help me? 请有人帮我吗?
Thank you. 谢谢。
Preg_match from / to _. 从/到_的Preg_match。
$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 https://3v4l.org/9oTuj
Performance of regex: 正则表达式的性能:
Since it's such a simple pattern you can also use normal substr with strrpos. 由于这是一个简单的模式,因此您也可以将正常的substr与strrpos一起使用。
Edited to use strrpos to get the last / 编辑使用strrpos获得最后一个/
$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 https://3v4l.org/d411c
Performnce of substring: 子字符串的性能:
My conclusion 我的结论
Regex is not suitable for this type of job as it's way to slow for such a simple substring pattern. 正则表达式不适用于这种类型的工作,因为它会减慢这种简单的子字符串模式的速度。
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. 使用explode函数代替preg_match可以轻松获得期望的输出。 And using preg_match, do like this: 并使用preg_match,如下所示:
<?php
$img = "path/myPhotoName_20170818_111453.jpg";
preg_match("/path\/(.+)\_[0-9]*\_[0-9]*\.jpg/", $img, $folder);
print_r($folder[1]);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.