删除最后一个'-';从PHP中的字符串

删除最后一个'-';从PHP中的字符串,php,string,substr,Php,String,Substr,我有一个脚本,可以处理当前文件的文件名并将其转换为标题 e、 g.morse-1.1.1.php使用以下命令将其转换为“morse”: <?php function pageInfo($type) { $http = "http://"; $server = $_SERVER["SERVER_NAME"]; $filePath = $_SERVER["REQUEST_URI"]; $fileName = basename($_SERVER["PHP_SELF

我有一个脚本,可以处理当前文件的文件名并将其转换为标题

e、 g.morse-1.1.1.php使用以下命令将其转换为“morse”:

<?php
function pageInfo($type) {
    $http = "http://";
    $server = $_SERVER["SERVER_NAME"];
    $filePath = $_SERVER["REQUEST_URI"];
    $fileName = basename($_SERVER["PHP_SELF"]);

    // creating version by removing letters up to dash
    $position = strpos($fileName, '-');
    $version = str_replace(".php", "", $fileName);

    switch ($type) {
        case "title":
            $title = ucwords(substr($fileName, 0, $position));
            return $title;
            break;
        case "version":
            $numVersion = substr($version, $position+1);
            return "Version ".$numVersion;
            break;
        case "url":
            return $http.$server.$fileName;
            break;
    }

}

echo pageInfo("title");
?>

我的问题是,我想在页面“caeser-shift-2.1.php”上使用相同的脚本,但目前我的函数只查找第一个“-”,并基于此删除字符。 如何调整函数以删除文件名中最后一个“-”的字符?

使用函数而不是strpos

$position = strrpos($fileName, '-');

您可以使用一个简短的正则表达式:

(.*)-.*
演示:

PHP:

输出:

卡塞尔位移


可能重复感谢你,这样一个简单的解决方案-我缺乏php中的字符串操作知识
(.*)-.*
echo preg_replace('~(.*)-.*~', '$1', 'caeser-shift-2.1.php');