title tag function
-
16-10-2019 - |
Question
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?
Solution
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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange