因此,测试用例字符串可能是:
http://example.com/?u=ben
或
http://example.com
我试图删除最后一次出现'/‘之后的所有内容,但前提是它不是'http://'’的一部分。这可能吗!?
到目前为止,我有这样的想法:
$url = substr($url, 0, strpos( $url, '/'));
但不起作用,去掉第一个'/‘之后的所有内容。
发布于 2012-05-25 07:42:30
您应该使用专为此类作业设计的工具parse_url
url.php
<?php
$urls = array('http://example.com/foo?u=ben',
'http://example.com/foo/bar/?u=ben',
'http://example.com/foo/bar/baz?u=ben',
'https://foo.example.com/foo/bar/baz?u=ben',
);
function clean_url($url) {
$parts = parse_url($url);
return $parts['scheme'] . '://' . $parts['host'] . $parts['path'];
}
foreach ($urls as $url) {
echo clean_url($url) . "\n";
}
示例:
·> php url.php
http://example.com/foo
http://example.com/foo/bar/
http://example.com/foo/bar/baz
https://foo.example.com/foo/bar/baz
发布于 2013-05-26 19:12:18
必须使用strrpos函数,而不是strpos ;-)
substr($url, 0, strrpos( $url, '/'));
发布于 2018-04-04 18:26:14
实际上,要实现这个目标,一个更简单的解决方案是使用PHP的几个字符串操作函数。
首先,您需要找到'/‘最后一次出现的位置。您可以通过使用strrpos()函数(小心,它是2 r)来完成此操作;
然后,如果您将此位置作为负值提供给substr()函数的第二个参数,它将从末尾开始搜索子字符串。
第二个问题是,您想要最后一个'/‘左边的字符串部分作为结果。为此,您必须为第三个参数提供substr()一个负值,该参数将指示您希望删除多少个字符。
为了确定需要删除多少参数,您必须首先提取'/‘右侧的字符串部分,然后计算其长度。
//so given this url:
$current_url = 'http://example.com/firstslug/84'
//count how long is the part to be removed
$slug_tbr = substr($current_url, strrpos($current_url, '/')); // '/84'
$slug_length = strlen(slug_tbr); // (3)
/*get the final result by giving a negative value
to both second and third parameters of substr() */
$back_url = substr($current_url, -strrpos($current_url, '/'), -$slug_length);
//result will be http://example.com/firstslug/
https://stackoverflow.com/questions/10746695
复制相似问题