删除结尾'-'PHP中的字符串


Remove Characters After the Final '-' From String in PHP

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

将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函数代替strpos。

$position = strrpos($fileName, '-');
$str = "some-test-texts-crop;
$data = substr($str , 0 , strrpos($str ,"-") )

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

(.*)-.*

演示:https://regex101.com/r/xR1sF1/1

PHP:

echo preg_replace('~(.*)-.*~', '$1', 'caeser-shift-2.1.php');
输出:

caeser-shift