PHP-如何在扩展名后删除所有内容(jpg,png,gif,jpeg,svg等)

我正在使用php 7,并尝试在扩展网址后删除所有内容;


例子


    https://website/sites/tag/filename/IMG25.jpg?iabc=gfds

    to 

    https://website/sites/tag/filename/IMG25.jpg

或者


    https://website/sites/tag/filename/IMG25.png&iabc=gfds

    to 

    https://website/sites/tag/filename/IMG25.png

或者


    https://website/sites/tag/filename/IMG25.jpeg&abc=gfds

    to 

    https://website/sites/tag/filename/IMG25.jpeg

我正在尝试此功能


$clean_url = preg_replace(

    "/(.+\.(:?jpg|gif|jp2|png|bmp|jpeg|svg)).*$/",

    '',

    $filename

);

但是这个功能不起作用


慕妹3242003
浏览 156回答 2
2回答

波斯汪

我已经对您的正则表达式进行了一些调整,以捕获组并仅将第一个组替换为url,如下所示:$clean_url = preg_replace(&nbsp; &nbsp; "/(.+(\.(jpg|gif|jp2|png|bmp|jpeg|svg)))(.*)$/",&nbsp; &nbsp; '${1}',&nbsp; &nbsp; $url);所有情况的示例代码:<?php$urls = [&nbsp; &nbsp; "https://website/sites/tag/filename/IMG25.png&iabc=gfds",&nbsp; &nbsp; "https://website/sites/tag/filename/IMG25.jpg?iabc=gfds",&nbsp; &nbsp; "https://website/sites/tag/filename/IMG25.jpeg&abc=gfds"];foreach ($urls as $url){&nbsp; &nbsp; $clean_url = preg_replace(&nbsp; &nbsp; &nbsp; &nbsp; "/(.+(\.(jpg|gif|jp2|png|bmp|jpeg|svg)))(.*)$/",&nbsp; &nbsp; &nbsp; &nbsp; '${1}',&nbsp; &nbsp; &nbsp; &nbsp; $url&nbsp; &nbsp; );&nbsp; &nbsp; echo $clean_url ."\n";}

翻翻过去那场雪

您可以这样操作:首先使用“?”展开您的网址字符串&nbsp;作为定界符,而不是使用结果数组的第一个元素。explode('?',&nbsp;$url)[0];
打开App,查看更多内容
随时随地看视频慕课网APP