简体   繁体   English

PHP正则表达式以确切的给定模式进行搜索

[英]PHP regex to search in the exact given pattern

i want to give regex a pattern and force it to read it all .. 我想给正则表达式一个模式,并强迫它阅读所有..

http://example.com/w/2/1/x/some-12345_x.png

i want to target "some-12345_x" 我想定位“ some-12345_x”
i used this /\\/(.*).png/ , it doesnt work for some reason 我用这个/\\/(.*).png/ ,由于某种原因它不起作用

how do i force it to remember it must start with / and end with .png? 我如何强迫它记住它必须以/开头并以.png结尾?

You can do: 你可以做:

^.*/(.*)\.png$

which captures what occurres after the last / till .png at the end. 捕捉什么occurres在最后/直到.png结尾。

If you always want to get the final file-name, minus the extension, you could use PHP's substr() instead of trying to come up with a regex: 如果您总是想要获得减去扩展名的最终文件名,则可以使用PHP的substr()而不是尝试使用正则表达式:

$lastSlash = strrpos($url, '/') + 1;
$name = substr($url, $lastSlash, strrpos($url, '.') - $lastSlash);

Also, a more readable method would be to use PHP's basename() : 另外,更易读的方法是使用PHP的basename()

$filename = basename($url);
$name = substr($filename, 0, strpos($filename, '.'));

To actually use a regex, you could use the following pattern: 要实际使用正则表达式,可以使用以下模式:

.*/([^.]+).png$

To use this with PHP's preg_match() : 将此与PHP的preg_match()

preg_match('|.*/([^.]+).png$|', $url, $matches);
$name = $matches[1];

You might need to use reg-ex in this situation for a particular reason, but here's an alternative where you don't: 在某些情况下,您可能出于某种特定原因需要使用reg-ex,但是您可以使用以下替代方法:

$url = "http://example.com/w/2/1/x/some-12345_x.png";
$value = pathinfo($url);
echo $value['filename'];

output: 输出:

some-12345_x

pathinfo() from the manual 手册中的pathinfo()

How about: 怎么样:

~([^/]+)\.png$~

this will match anything but / until .png at the end of the string. 这将匹配/直到字符串末尾的.png为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM