PHP 在字符串中最后一次出现字符后删除字符 [英] PHP remove characters after last occurrence of a character in a string
本文介绍了PHP 在字符串中最后一次出现字符后删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以测试用例字符串可能是:
So the test case string may be:
http://example.com/?u=ben
或
http://example.com
我试图在最后一次出现/"之后删除所有内容,但前提是它不是http://"的一部分.这可能吗!?
I'm trying to remove everything after the last occurrence of a '/' but only if it's not part of the 'http://'. Is this possible!?
到目前为止我有这个:
$url = substr($url, 0, strpos( $url, '/'));
但不起作用,在第一个/"之后去掉所有内容.
But does not work, strips off everything after first '/'.
推荐答案
您应该使用专为此类工作设计的工具 parse_url
You should use the tool that is designed for this type of job, 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
这篇关于PHP 在字符串中最后一次出现字符后删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文