PHP return 平面文件中 $title 变量的值

PHP return value of $title variable from a flat file

我正在编写一个脚本,其中 returns 位于 php 文件顶部的 $title 变量的文字值。在脚本的末尾,我使用 rtrim() 删除字符串末尾的引号和分号,但是它们不会 trim。我的 php 文件的顶部如下所示:

<php
$title="Test Title";
$description="Test Description";
?>

当我回显字符串时,我得到:

Test Title;"

这是我的代码。谁能告诉我我做错了什么?我什至欢迎提出任何改进建议:

<?php
//returns the value of the $title variable from the top of a php file.
$file = fopen("test.php", "r") or die("Unable to open file!");
$count = 0;
while ($count < 10) {                   //only check the first 10 lines
    $line = fgets($file);
    $isTitle = strpos($line, "itle=");         //check if $title is part of the string
    if ($isTitle !== false) {
        $fullTitle = explode("=\"", $line);      //explode it into two on =" which also trims the first quote
        $untrimmedTitle = $fullTitle[1];         //save the second part of the array as a string since rtrim needs a string
        $title = rtrim($untrimmedTitle, "\";");    //trim the quote and semi-colon from the string 
        $count = 10;                               //push the count up to 10 so it ends the loop
    }
    $count++;
}
echo $title;                                //show the title
fclose($file);
?>

行中:

$title = rtrim($untrimmedTitle, "\";");

您正在从字符串中 triming ";。你想要 trim ';:

$title = rtrim($untrimmedTitle, "\';");

编辑:

为什么不这样做:

include "test.php";
echo $title;

?

$title = rtrim($untrimmedTitle, "\";"); 更改为 $title = rtrim(trim($untrimmedTitle), "\";");。会好的。

在 $untrimmedTitle 的末尾有一个中断,如 \n

或者您可以这样做:

$title = rtrim($untrimmedTitle, "\";\n");