PHP删除web地址字符串中的.html之后的所有内容
我正在尝试删除在web地址字符串中包含“.html”之后的所有内容。当前(失败)代码为: 预期结果:PHP删除web地址字符串中的.html之后的所有内容,php,regex,Php,Regex,我正在尝试删除在web地址字符串中包含“.html”之后的所有内容。当前(失败)代码为: 预期结果: value of $result is 'http://example.com/somepage' 其他一些$input示例应导致相同的$result值: http://example.com/somepage http://example.com/somepage.html http://example.com/somepage.html?url=http://example.com/ind
value of $result is 'http://example.com/somepage'
其他一些$input示例应导致相同的$result值:
http://example.com/somepage
http://example.com/somepage.html
http://example.com/somepage.html?url=http://example.com/index.html
您的常规表达式错误,它只匹配以
“html”
结尾的字符串。由于preg\u replace
仅返回字符串“原样”,如果不匹配,则可以匹配文本.html
,并忽略其后的任何内容:
$result = preg_replace('/\.html.*/', '', $input);
为什么不改为使用?如果您对preg_replace()的语法有任何问题,那么您也可以使用explode():
我喜欢这里的简单。(将与中断,是的,这是一个可能的url哈哈)否--“.html”作为分隔符,因此上述解决方案在您的示例中不会中断。如果您将“,”视为CSV字符串中的分隔符,这将是相同的。返回数组中的path元素是否仍包含.html?它将包含,但一个简单的rtrim将删除它,您只需使用内置函数即可解决问题。解析url不就是在后台使用regex吗?
$result = preg_replace('/\.html.*/', '', $input);
$input = explode(".html", $input);
$result = $input[0];