PHP - 从字体 URL 中删除查询字符串

PHP - Remove query string from font URLs

我在 PHP 变量中有这个字符串(示例):

@font-face {  
    src: url('../some-font.eot?v=4.6.3');
}

我需要在每一行上按 .eot? 进行搜索。如果找到,请进行替换,结果为:

@font-face {      
    src: url('../some-font.eot');
}

如有任何帮助,我们将不胜感激。

这里有一些宽泛的正则表达式(它几乎可以匹配第一个 ? 之前的所有内容)但这应该为您提供路径的起点:

echo preg_replace("/^([^?]+).*/", "", "../some-font.eot?v=4.6.3");

打印:

../some-font.eot

您需要删除锚点并添加一些上下文以在整个文件中进行搜索,例如使用正向回顾。

echo preg_replace("/(?<=src: url\(')([^?]+)[^']*?/", "", "src: url('../some-font.eot?v=4.6.3');");

打印:

src: url('../some-font.eot');

lookbehind 将确保您最终只会替换您关心的 URL(例如,它不会触及评论、content 属性等)。

搜索字符串,然后搜索不是您的结束封装字符的所有内容。

eot\?[^'"]+

正则表达式演示:https://regex101.com/r/SEPPHc/1/

PHP 演示:https://eval.in/761197

PHP:

$string = "@font-face {  
    src: url('../some-font.eot?v=4.6.3');
}";
echo preg_replace('/eot\?[^\'"]+/', 'eot', $string);

直接使用 \Q...\E 序列:

\Q.eot?\E[^'")]+

将其替换为 .eot 并查看 a demo on regex101.com\Q...\E 序列将内部的所有字符视为普通文字,因此不需要转义。