Jonathan Nuñez
Jonathan Nuñez

Reputation: 422

Check URL parameter in php

I want to check a parameter in a url variable, for example:

$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';

first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.

Wanted output:

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

I tried:

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

Upvotes: 0

Views: 97

Answers (2)

TimBrownlaw
TimBrownlaw

Reputation: 5507

This is a little generic function with some support code to give you some ideas... Not very elegant but it works.

<?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;
}

Upvotes: 1

Don&#39;t Panic
Don&#39;t Panic

Reputation: 14510

Use parse_url(), it is specifically for analysing URLs and their various elements.

Note this code assumes your parameters are path segments, as you describe above. If you ever use query string parameters like ?foo=bar, you'd need to adjust.

$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;

Upvotes: 3

Related Questions