使用变量PHP Regex删除URL的结尾

问题描述 投票:-2回答:2

我在regex上suuuuuck,甚至无法开始弄清楚如何从#edit中删除所有内容,其中包含来自此类URL的url的可验证:

https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4/edit?usp=sharing

任何帮助将不胜感激!

谢谢!

php regex
2个回答
0
投票

使用strstr()和第三个参数设置为true将是最干净,最直接的非正则表达式方法。 ...而且你不必冒汗“suuuuucky”正则表达式技能;)这会将子串从字符串的开头隔离到搜索子字符串之前的字符。

代码:(Demo

$url = 'https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4/edit?usp=sharing';

echo strstr($url, '/edit', true);  // https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4
echo "\n";
echo strstr($url, '/edit?', true);  // https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4

*注意:如果查询字符串(以qazxsw poi开头)将始终存在于qazxsw poi之后,则将?添加到搜索子字符串只能提高准确性。

为什么这是最好的功能?它不利用调用正则表达式引擎的开销,它不生成任何临时数组,并且它是单个函数调用,而不是/edit-?

如果你的用例有点复杂并且这种方法让你失望,那么调用substr()应该足够稳定,以便你提取适当的url组件。

代码:(strrpos()

parse_url()

0
投票

我相信你正试图解析网址末尾的Demo。您可以使用$url = 'https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4/edit?usp=sharing'; $components = parse_url($url); echo $components['scheme'], '://', $components['host'], strstr($components['path'],'/edit',true); 函数执行此操作:

query parameters

这将打印

explode
© www.soinside.com 2019 - 2024. All rights reserved.