How can I extract a word from page/post URL using shortcodes

<?php
 function url_fetcher(){
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } 
    else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }


    //echo $pageURL;
    $str = explode("https://wordpress.stackexchange.com/" ,$pageURL);
    //print_r($str);

    $str1 = $str[3];
    echo $str1.'<br \>';
    $str2 = explode("-", $str1);
    $cat = $str2[0];
    echo $cat.'<br \>';
    $dog = $str2[2];
    echo $dog.'<br \>';
 }

 add_shortcode('url_fetch','url_fetcher');
?>

Add the shortcode [‘url_fetch’] where you want them. But make sure that your url has the page names seperated by hyphens(‘-‘).Specifically cat-to-dog or a-to-b.