emporio emporio - 6 months ago 12
PHP Question

Do something if url is exact match in php

I want to run some code if there is an exact url match.

I currently have this:

//Returns 'https://www.someurl.com'
$browserUrl = curPageURL();


Now I have one line that is meant to build a new url based on
$browserUrl
. For that I have created this:

<?php
//Gets the url of a specific page
$page = icl_object_id(2880, 'page', true);
$url = get_permalink($page);
//Cplits the url into useful parts for rebuilding
$parts = explode("/", $url);
?>

//Here I am rebuilding the url based on the url I retrieved with the code above
<a href="<?php echo curPageURL() . $parts[4] . '#sendMessage'; ?>"><?php _e('Send us an Email','optionsBlock'); ?></a>


But, by using a ternary operator, what I am actually trying to do is this:

<a href="<?php echo curPageURL() . $browserUrl == 'https://www.someurl.com' ? $parts[3] : $parts[4] . '#sendMessage'; ?>"><?php _e('Send us an Email','optionsBlock'); ?></a>


But this is not working as expected because it is not picking up direct url match. Is this the right way to do it?

Answer

If what you want is to use $parts[3] or $parts[4] depending on the $browserUrl check, and the ternary operator is the problem, then I suggest to make a new variable, let's say $part, holding the result of the ternary operator, then use it in the concatenation, like this:

<?php
   //Gets the url of a specific page
   $page = icl_object_id(2880, 'page', true);
   $url = get_permalink($page);
   //Cplits the url into useful parts for rebuilding
   $parts = explode("/", $url);
   $part = $browserUrl == 'https://www.someurl.com' ? $parts[3] : $parts[4];
?>

//Here I am rebuilding the url based on the url I retrieved with the code above
<a href="<?php echo curPageURL() . "{$part}#sendMessage"; ?>"><?php _e('Send us an Email','optionsBlock'); ?></a>

Or you can use the ternary operator inside the concatenation, but you need to enclose it in brackets to work properly, like this:

<a href="<?php echo curPageURL() . ($browserUrl == 'https://www.someurl.com' ? $parts[3] : $parts[4]) . '#sendMessage'; ?>"><?php _e('Send us an Email','optionsBlock'); ?></a>

Personally I don't like this, as it's somewhat confusing to read.