正则表达式在url中获取文件类型

正则表达式在url中获取文件类型

问题描述:

I am using a converter that accepts Regex to do a mass "search and replace" in a database to change all .png to .jpg. Consider the following where a link to an image is mixed in with a lot of HTML code (simplified example):

bunch_of_text_http:// somewebsite.com/somepath/somefile.png_bunch_of_text

The "bunch_of_text" and "some-x" are all variables.

For clarification, the only .png's I need changed must follow a mostly prescribed URL. For example, I need to replace all .png's on the example.com domain but not on other domains. Here's another example:

Convert: http://example.com/images/XX/YY/filename.png to http://example.com/images/XX/YY/filename.jpg

WHERE

XX and YY are variables and may be at any level of depth in the folder structure.

But ignore any other domain other than example.com.

The code on the backend is written in PHP.

I need one line of Regex code to return only the ".png" text so my script can replace that with ".jpg". Any help is greatly appreciated.

我使用的转换器接受Regex在数据库中进行大规模“搜索和替换”以更改所有内容。 png到.jpg。 请考虑以下内容,其中图像的链接与许多HTML代码混合在一起(简化示例): p>

bunch_of_text_http:// somewebsite.com/somepath/somefile.png_bunch_of_text

“bunch_of_text”和“some-x”都是变量。 p>

为了澄清,我需要更改的唯一.png必须遵循大部分规定的URL。 例如,我需要替换example.com域上的所有.png,而不是其他域。 这是另一个例子: p>

转换: http ://example.com/images/XX/YY/filename.png http://example.com/images/XX/YY/filename.jpg p>

WHERE p>

XX和 YY是变量,可以处于文件夹结构中的任何深度级别。 p>

但是忽略除example.com之外的任何其他域。 p>

后端的代码是用PHP编写的。 p>

我需要一行正则表达式代码才能返回“.png”文本,所以我的脚本可以用“.jpg”替换它。 非常感谢任何帮助。 p> div>

$url = "http://example.com/images/XX/YY/filename.png";
$result = preg_replace(';(http://example.com/images/.*?/.*?/.*?)\.png;', '$1.jpg', $url);
echo $result;

Some regular expression explanation: https://regex101.com/r/2ZDzq0/1

Note I've replaced the usual / delimiter with ; because it's easier when working with URLs.

If literally all you want to return is ".png", then all you need is \.png.

That will match an instance of ".png". You would then do a Find And Replace All operation:

Find All:   \.png
Replace:    \.jpg

If your question is more complicated than that (i.e. only return ".png" if its context is such-and-such), then please clarify your question.

Here is the answer: https://regex101.com/r/QIgKX9/1

Thanks everyone!