如何在PHP中只提取部分字符串? [英] How to extract only part of string in PHP?

查看:18
本文介绍了如何在PHP中只提取部分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下字符串,我想提取Image123.jpg。

..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length

Image123可以是任意长度(newImage123456等),扩展名为jpg、jpeg、gif或png。

我假设我需要使用preg_match,但我不是很确定,也不想知道如何编码,或者是否有任何其他方法或函数可以使用。

推荐答案

您可以使用:

if(preg_match('#".*?/(.*?)"#',$str,$matches)) {
   $filename = $matches[1];
}

或者,您可以使用preg_Match提取双引号之间的完整路径,然后使用函数basename

从路径中提取文件名
if(preg_match('#"(.*?)"#',$str,$matches)) {
    $path = $matches[1]; // extract the entire path.
    $filename =  basename ($path); // extract file name from path.
}

这篇关于如何在PHP中只提取部分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆