解决方案#1,使用substr() + strrpos():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$pos = strrpos($string, '/');
if ($pos !== FALSE) {
echo(substr($string, 0, $pos + 1));
}
函数strrpos() 查找/ 在字符串中最后一次 出现的位置,substr() 提取所需的子字符串。
缺点:如果$string 不包含'/',strrpos() 将返回FALSE 并且substr() 不会返回我们想要的。需要先检查strrpos()返回的值。
解决方案#2,使用explode() + implode():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$array = explode('/', $string);
if (count($array) > 1) {
array_pop($array); // ignore the returned value, we don't need it
echo(implode('/', $array).'/'); // join the pieces back, add the last '/'
}
或者,我们可以将最后一个组件设为空而不是array_pop($array),并且无需在末尾添加额外的'/':
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$array = explode('/', $string);
if (count($array) > 1) {
$array[count($array) - 1] = ''; // empty the last component
echo(implode('/', $array)); // join the pieces back
}
缺点(对于两个版本):如果$string 不包含'/',explode() 会生成一个包含单个值的数组,其余代码会生成'/' (第一段代码)或空字符串(第二段)。需要检查explode()产生的数组中的项数。
解决方案#3,使用preg_replace():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
echo(preg_replace('#/[^/]*$#', '/', $string));
缺点:无。当$string 包含'/' 和不包含'/'(在这种情况下它不会修改$string)时,它都能正常工作。