检查php中的URL参数

时间:2017-12-09 01:58:21

标签: php string

我想检查url变量中的参数,例如:

$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';

首先检查$ url变量是否将$ var2join作为参数加入$ var作为参数,如果有,请保持原样,如果没有添加它。

通缉输出:

$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';

我试过了:

$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;

2 个答案:

答案 0 :(得分:3)

使用parse_url(),它专门用于分析网址及其各种元素。

请注意,此代码假定您的参数是路径段,如上所述。如果您使用?foo=bar之类的查询字符串参数,则需要进行调整。

$var2join = 'en';
$url = 'https://www.example.com/hello/parameter2';

// Split URL into each of its parts
$url_parts = parse_url($url);

// Create an array of all the path parts, which correspond to
// parameters in your scheme
$params = explode('/', $url_parts['path']);

// Check if your var is in there    
if (!in_array($var2join, $params)) {

    // If not, reconstruct the same URL, but with your var inserted.
    // NOTE this assumes a pretty simple URL, you'll need to adjust if
    // you ever have other elements like port number, u/p, query strings
    // etc.  @Jason-rush links to something in the PHP docs to handle
    // such cases.
    $url = $url_parts['scheme'] . '://' . $url_parts['host'] . '/' . $var2join . $url_parts['path']; 
}

// Check your result - https://www.example.com/en/hello/parameter2 
echo $url;

答案 1 :(得分:1)

这是一个通用的小功能,有一些支持代码可以给你一些想法...不是很优雅,但它有效。

<?php

$base_url = 'https://www.example.com/';
$var2join = 'en'; // can be anything else

$url = $base_url . 'hello/parameter2';
$url2 = $base_url . 'hello2';
$url3 = $base_url . 'en/hey';
$url4 = $base_url . 'hey/this/is/longer';



echo prepend_path_to_url($base_url, $url, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url2, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url3, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url4, $var2join);
echo '<br>';

/**
 * Prepend a Path to the url
 *
 * @param $base_url
 * @param $url
 * @param $path_to_join
 * @return string
 */
function prepend_path_to_url($base_url, $url, $path_to_join) {
    // Does the path_to_join exist in the url
    if (strpos($url, $path_to_join) === FALSE) {
        $url_request = str_replace($base_url,'',$url);
        $url = $base_url . $path_to_join . '/'. $url_request;
    }
    return $url;
}