0

I am using a function to display the URL on title tag, I coded this function which works properly but I would like to customize it more further.

function title_tag()
{
$a = $_SERVER['REQUEST_URI'];
$b = strtoupper($a);
$c = str_replace('-', ' ', $b);
$d = str_replace('/', ' - ', $c);

$e = substr($d, 2);
return $e;
}

This function will display the url on title after inserting this code in title tag.

<title><?php echo title_tag(); ?></title>

The current code is displaying the title in this format, my title of website:

STANFORD UNIVERSITY - MBA IN CALIFORNIA - MBA -

But I want to display it in this format, just the change in punctuations

STANFORD UNIVERSITY - MBA IN CALIFORNIA, MBA -

Just a comma as separator in between How can I have this?

1
function title_tag () {

    // 0. uppercase string
    $str = strtoupper ( $_SERVER['REQUEST_URI'] );

    // 1. remove trailing and init slash
    $str = trim ( $str , '/' );

    // 2. add search and replace chars; 
    // two array, with same element size, 
    // 1. element of search array will be replaced
    // with the first element of replace array
    $search = array (
        '-',
        '/'
    );

    $replace = array (
        ' ',
        ' - '
    );

    // 3. replace the chars
    $str = str_replace( $search , $replace , $str );

    // 4. replace the last occurance of - for ,
    // $pos finds the position of the last occurance
    // and fortunately, PHP strings can be manipulated 
    // as arrays, so replace the array element with the
    // character
    $pos = strrpos ( $str , '-' );
    $str{$pos} = ',';

    // you're ready
    return $str;
}
  • hey this really worked and solved my problem, thanks for your help – Niraj Chauhan Mar 26 '11 at 9:11
  • the trick was with the trim function, to replace all unwanted / chars, from both the begining and the end of the query string, so you could be sure your want to replace the last - char – petermolnar Mar 26 '11 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.