【问题标题】:Check url for if condition检查 url 的 if 条件
【发布时间】:2015-11-04 09:17:13
【问题描述】:

所以,我对 wordpress 网站有以下条件:

if (is_page(array(1111, ???)) {
//do something for page# 1111 and url that contains "names"
}

我有一个网址如下:

example.com/names/steve
example.com/names/mike

所以,我想检查 url 是否为“names”作为条件。

谁能告诉我如何更改条件以检查 url 中的“名称”?

谢谢

编辑:

我改成了下面的,但还没有运气。

if ((is_page(1111)) || (preg_match("/\/names$/", $_SERVER['REQUEST_URI']))) 

or

if ((is_page(1111)) || (basename($_SERVER['REQUEST_URI']) == 'names')) 

or

if ((is_page(1111)) || (strpos($url, 'names') !== false))

有什么建议吗?

【问题讨论】:

  • strpos($url, 'names') !== false
  • 你使用了不需要的括号

标签: php wordpress


【解决方案1】:

使用正则表达式的preg_match()函数:

<?php
    $url = 'example.com/names/steve';
    echo (preg_match("/names/i", $url)) ? 'Match' : 'No Match';
?>

所以你的例子试试这个:

if (is_page(1111) || preg_match("/\/names\//", $_SERVER['REQUEST_URI'])){
   // your logic
}

【讨论】:

    【解决方案2】:
    $link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $myArray = explode("/", $link);
    $page = end($myArray);
    if($page == '1111') {
      //Your code
    }
    

    编辑:如果 URL 包含斜杠(或不包含)

    $link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $actual_link = rtrim('/', $link);
    $myArray = explode("/", $actual_link);
    $page = end($myArray);
    if($page == '1111') {
      //Your code
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多