php:如果当前url包含“/ demo”做某事

时间:2014-01-30 13:43:49

标签: php url conditional-operator

我想检查我当前的网址是否在网址末尾包含“/ demo”,例如mysite.com/test/somelink/demo来执行某些操作。 这是我的尝试:

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'mysite.com/test/somelink/demo') 
 {
// Do something
}
else
{
// Do something
}

这似乎工作正常,但问题是/somelink需要通过动态。

有关如何执行此操作的任何建议?

谢谢!

修改:

<?php
/* An abstract class for providing form types */
abstract class ECF_Field_Type {
    private static $types = array();
    protected $name;

    /* Constructor */
    public function __construct() {
        self::register_type( $this->name, $this );
    }

if(basename($_SERVER['REQUEST_URI']) == 'stats'){
echo "Hello World";
}

    /* Display form field */

    public abstract function form_field( $name, $field );

    /* Display the field's content */
    public function display_field( $id, $name, $value ) {
        return "<span class='ecf-field ecf-field-$id'>"
            . "<strong class='ecf-question'>$name:</strong>"
            . " <span class='ecf-answer'>$value</span></span>\n";
    }


    /* Display field plain text suitable for email display */
    public function display_plaintext_field( $name, $value ) {
        return "$name: $value";
    }

    /* Get the description */
    abstract public function get_description();
}
?>

5 个答案:

答案 0 :(得分:3)

只需使用,

if(basename($_SERVER['REQUEST_URI']) == 'demo'){
    // Do something
}

答案 1 :(得分:1)

<?php
    if (preg_match("/\/demo$/", $_SERVER['REQUEST_URI'])) {
        // Do something
    } else {
        // Do something else
    }
?>

答案 2 :(得分:0)

This post有PHP代码,可以使用PHP中的简单startsWidth()和endsWith()函数。您的代码最终会如下所示:

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith($host, '/demo'))
{
// Do something
}
else
{
// Do something
}

但除此之外你可能想做的一件事是将$ host转换为小写,所以URL的大小写无关紧要。 编辑:这最终会像这样:

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith(strtolower($host), '/demo'))

答案 3 :(得分:0)

您可以使用strpos

$host = 'mysite.com/test/somelink/demo';
if(strpos($host,'demo')) 
  {
// Do something 
   echo "in Demo";
}
else
{
// Do something
 echo "not in Demo";
}

答案 4 :(得分:0)

$str = 'demo';
if (substr($url, (-1 * strlen($str))) === $str) { /**/ }