【问题标题】:PHP - If page URL = "http://example.com/page", display image. Else, display another imagePHP - 如果页面 URL = "http://example.com/page",则显示图像。否则,显示另一个图像
【发布时间】:2015-03-16 18:16:35
【问题描述】:

我有我的模板,如果您在某个页面上,例如 http://example.com/test,我希望它显示某个图像,并且如果您不在该页面上,那么 我想要它以显示另一张图片

我还希望它显示图像如果您在任何子目录中,例如http://example.com/test/stuff

另外,有没有办法在同一代码中处理多个页面?

很喜欢

if page = example.com/test then display testimg.jpg

if page = example.com/archive then display archive.jpg

else, display defaultimg.jpg

谢谢!

【问题讨论】:

标签: php url if-statement selection


【解决方案1】:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if ( strpos($url, 'test') !== false ) {
    echo('<img src="image_path/testimg.jpg">');
}
elseif ( strpos($url, 'archive') !== false ) {
    echo('<img src="image_path/archive.jpg">');
}
else {
    echo('<img src="image_path/defaultimg.jpg">');
}

【讨论】:

  • 函数 strpos() 可能返回布尔值 FALSE,但也可能返回计算结果为 FALSE 的非布尔值。请阅读有关布尔值的部分以获取更多信息。使用 === 运算符测试此函数的返回值。 php.net/manual/en/function.strpos.php
【解决方案2】:

你也可以使用 strpbrk() 函数并获得更紧凑的代码:(>PHP5)

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if ( strpbrk($url, 'test') ) {
    echo('<img src="image_path/testimg.jpg">');
}
elseif ( strpbrk($url, 'archive') ) {
    echo('<img src="image_path/archive.jpg">');
}
else {
    echo('<img src="image_path/defaultimg.jpg">');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2012-01-27
    相关资源
    最近更新 更多