应该使用哪个PHP数组函数将字符串与分隔线的第一部分匹配并返回分隔线的第二部分


Which PHP Array Function Should Be Used To Match a String to the First Part of a Delimited Line and Return the Second Part of the Delimited Line

应该使用哪个php数组函数将字符串与分隔行的第一部分匹配,并返回分隔行的第二部分?我之所以使用数组,是因为我在一个文件中有许多分隔的文本行。例如:

contact-us.php = Contact Us- Test Bed

我需要一些方法来将页面文件名与分隔行的第一部分匹配,并返回它的第二部分。我尝试了几个不同的数组函数,但我不知道该使用哪一个,也不知道如何实现数组函数,假设我找到了正确的数组函数。这是我设计的代码,它位于php文件的头部。一旦选择了正确的页面标题,我只需将其打印到标题标签中。

function getPageName()
{
    return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); // If one echo's this and the url is /TestBed/contact-us.php Output will be: contact-us.php
}
function pageTitleIdentifier ()
{
    $filename = 'http://localhost/TestBed/includes/apptop/title.txt';
    $mode = 'rb';
    $file_handle = fopen ($filename, $mode);
    while (!feof($file_handle) ) {
        $page_title_pair = fgets($file_handle); // This will start reading where the above while loop stopped line by line.
        $parts = explode('=', $page_title_pair);
        @ $pageTitle = $parts[0] . $parts[1]; // Part zero is the filename ex contact-us.php Part one is the Title ex Contact Us- Test Bed for that page.
    }
    fclose($file_handle);
}

那么,正确的方法是什么呢?非常感谢!

首先,您可能需要考虑实现一个缓存解决方案。在高流量服务器上为每个请求解析一个文件,肯定会增加不必要的负载。

试试这个:

function pageTitleIdentifier ()
{
    $filename = 'http://localhost/TestBed/includes/apptop/title.txt';
    $mode = 'rb';
    $file_handle = fopen ($filename, $mode);
    while (!feof($file_handle)) {
        $page_title_pair = fgets($file_handle); 
        list($script, $title) = explode('=', $page_title_pair);
        // Uncomment below lines for debugging, they must line up exactly
        //   for the condition to be met, breaking the loop
        // var_dump($script);
        // var_dump(getPageName();
        // Because we reading from a file, might be some whitespace issues
        //  trim and strtolower ensures a true apples to apples comparison
        if (trim(strtolower($script)) === trim(strtolower(getPageName()))) {
            return $title;
        }            
    }
    fclose($file_handle);
}