应该使用哪个PHP数组函数将字符串与分隔行的第一部分匹配,并返回分隔行的第二部分
应该使用哪个php数组函数将字符串与分隔行的第一部分匹配,并返回分隔行的第二部分?我之所以使用数组,是因为我在一个文件中有许多分隔的文本行。例:应该使用哪个PHP数组函数将字符串与分隔行的第一部分匹配,并返回分隔行的第二部分,php,arrays,explode,delimited-text,Php,Arrays,Explode,Delimited Text,应该使用哪个php数组函数将字符串与分隔行的第一部分匹配,并返回分隔行的第二部分?我之所以使用数组,是因为我在一个文件中有许多分隔的文本行。例: contact-us.php = Contact Us- Test Bed 我需要某种方法将页面文件名与分隔行的第一部分匹配,然后返回第二部分。我尝试了几个不同的数组函数,但如果找到了正确的数组函数,我不知道该使用哪一个,也不知道如何实现该数组函数。这是我设计的代码,它位于php文件的头部。一旦选择了正确的页面标题,我将简单地将其打印到标题标签中 f
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);
}
嗯,它不起作用了。它没有给出任何错误,即使设置为“通知”。我将这一行更改为
print_r(list($page,$title)=explode('=',$page_title_pair))代码>它打印这个:数组([0]=>index.php[1]=>Test Bed)数组([0]=>news.php[1]=>news-Test Bed)数组([0]=>contact-us.php[1]=>contact-us-Test Bed)数组([0]=>about.php[1]=>about-Test Bed)每一行都是一个新数组,但我认为$script在所有文件都被读取为$title后会被检查。我如何更改它,以便只读取一行,然后进行比较?执行var_dump(getPageName())并发布结果。显然情况并非如此,因为这样修改代码:print_r(list($page,$title)=explode('=',$page_title_pair));//$script是文件名ex contact-us.php$title是该页面的标题。打印“下一步”代码>打印这个:数组([0]=>index.php[1]=>testbed)NextArray([0]=>news.php[1]=>news-testbed)NextArray([0]=>contact-us.php[1]=>contact-us-testbed)NextArray([0]=>about.php[1]=>about-testbed)NextI会尝试一下。。。现在不行。你实际上回答了,我没有注意到,所以我上面的评论并不意味着你所说的不起作用,因为我的评论在某种程度上应该在你的上面。注意:文本文件中目前有4行。好的,当var_dump[…]在if循环中时,不会发生任何事情,这意味着if循环永远不会为真。