代码之家  ›  专栏  ›  技术社区  ›  vpetkovic

如何使用PHP修剪/隐藏文件扩展名并在页面上显示文件名?

  •  0
  • vpetkovic  · 技术社区  · 10 年前

    我创建了一个表单,用户从下拉菜单中选择日期和选项(其中列出了路径中的所有文件)并提交它。提交时,用户的输入会以某种格式写入其他文件,但也会显示在表单下方,以便用户可以看到最终输出。输出,特别是包含日期和基于所选选项的链接(用户可以进行多项选择)。

    例子:

    用户从日期选择器中选择08-01-2014 option1.txt 从下拉菜单中选择。现在已将其输出到 file.js 格式如下:

    '08-01-2014' : '<a href="/path/option1.txt" target="_blank"><span>option1.txt</span></a>',
    

    并且以这种格式显示在表单下方( option1.text是带下划线的,因为它是一个链接,但不知道我是否可以在此处加下划线以显示 ):

    08-01-2014 : option1.txt
    

    所以我的问题是,如何修改写下用户输入的代码,以便显示它的代码可以读取文件并显示 08-01-2014 : option1 没有 .txt .

    记录用户输入的PHP代码( 减记.php ):

    <?php
        $pickdate = $_POST['date'];
        $workout = $_POST['workout'];
        $date = '   \''.$pickdate .'\' : \'<a href="../routines/'.$workout.'" target="_blank"><span>'.$workout.'</span></a>\',' .PHP_EOL;
        $file = 'test.js';
    // Open the file to get existing content
        $current = file_get_contents($file);
    // Append a new workout to the file
        $current .= $date;
        $current = preg_replace('/};/', "", $current);
        $current = $current.'};';
    // Write the contents back to the file
        file_put_contents($file, $current);
        header( "location:index.php" );
    ?>
    

    在表单下面显示用户输入的PHP代码( 索引php ):

    <?php
        $file = "test.js";
        $current = file_get_contents( $file );
        $current = preg_replace('/var codropsEvents = {/', "", $current);
        $current = preg_replace('/,/', "<br>", $current);
        $current = preg_replace('/\'/', " ", $current);
        $current = preg_replace('/ /', " ", $current);
        $current = preg_replace('/};/', "", $current);
        //$current = preg_replace('/option1.txt/', "<a href='test.php'>option1</a>", $current);
        echo $current;
    ?>
    

    我尝试了我所知道的一切,我可以在互联网上找到,我能得到的最接近的是上面代码中的注释行

    //$current = preg_replace('/option1.txt/', "<a href='test.php'>option1</a>",
    

    它只适用于单个条目,我必须手动添加同一行,以便将其应用于其他条目。

    如有任何帮助,将不胜感激。

    2 回复  |  直到 10 年前
        1
  •  1
  •   swiss_blade    10 年前

    你可以用 basename 要从完整路径获取文件名:

    $filename = basename($url,'.txt');
    

    哪里 $url 是.txt文件的路径

        2
  •  0
  •   Cobra_Fast    10 年前

    您可以使用 preg_replace 使用正则表达式来完成工作。

    $current = preg_replace(
        '/(.+)\.(.{2,3})$/i',
        '<a href="test.php">\1</a>',
        $current
    );