我需要为我正在做的脚本动态创建标题,标题应该取决于当前使用的文件。
我的结构脚本是:
@require_once"bd.php";
@require_once"Funciones/functions.php";
include head.php;
include body.php;
include footer.php;
我的标题函数代码是从 head 调用的.php
这是我的函数,但不起作用总是返回空白结果:s
function get_title(){
$indexurl = "index.php";
$threadurl = "post.php";
$searchurl = "search.php";
$registerurl = "register.php";
$query = $_SERVER['PHP_SELF'];
$path = pathinfo( $query );
$url = $path['basename']; //This returns the php file that is being used
if(strpos($url,$indexurl)) {
$title = "My home title";
}
if(strpos($url,$threadurl)) {
$title = "My post title";
}
if(strpos($url,$searchurl)) {
$title = "My search title";
}
if(strpos($url,$registerurl)) {
$title = "My register page title";
}
return $title;
}
我调用函数:
<title><? echo get_title(); ?></title>
一个
更好的方法可以在这里找到,正如我在最初的评论中所说:https://stackoverflow.com/a/4858950/1744357
您应该将标识属性与 strpos 一起使用,并针对 FALSE 进行测试。
if (strpos($link, $searchterm) !== false) {
//do stuff here
}
我发现了问题:
$string = "This is a strpos() test";
if(strpos($string, "This)) {
echo = "found!";
}else{
echo = "not found";
}
如果您尝试执行它,您会发现它输出"未找到",尽管"This"显然在$string中。这是另一个区分大小写的问题吗?差一点。这次的问题在于"This"是$string的第一件事,这意味着strpos()将返回0。但是,PHP 认为 0 与 false 的值相同,这意味着我们的 if 语句无法区分"找不到子字符串"和"在索引 0 处找到子字符串" - 这是一个很大的问题!
因此,在我的情况下,使用 strpos 的正确方法是从 $indexurl、$threadurl、$searchurl 中删除第一个字符并$registerurl
function get_title(){
$indexurl = "ndex.php";
$threadurl = "ost.php";
$searchurl = "earch.php";
$registerurl = "egister.php";
$query = $_SERVER['PHP_SELF'];
$path = pathinfo( $query );
$url = $path['basename']; //This returns the php file that is being used
if(strpos($url,$indexurl)) {
$title = "My home title";
}
if(strpos($url,$threadurl)) {
$title = "My post title";
}
if(strpos($url,$searchurl)) {
$title = "My search title";
}
if(strpos($url,$registerurl)) {
$title = "My register page title";
}
return $title;
}