URI as <title> Mar20 '05
Let’s say this is my $_SERVER['REQUEST_URI'] variable:
/blog/
Instead of manually having to manage the <title> element for each requested page, I would rather use the variable above as my <title> element text:
<title>matthom :: <?php echo $_SERVER['REQUEST_URI']; ?></title>
This code would output:
matthom :: /blog/
It looks good, except... I don’t want the forward slashes in there. I just want the word.
I could effectively do one of two things.
String replace
Remove the forward slashes by replacing each occurence of a slash with an empty string:
# REPLACE THE SLASH AT THE VERY END
$title_temp = substr_replace($_SERVER['REQUEST_URI'], '', -1, 1);
# REPLACE THE SLASH AT THE VERY BEGINNING
$title = substr_replace($title_temp, '', 0, 1);
echo "<title>matthom :: ".$title."</title>";
Array
Remove the forward slashes by placing each part in an array:
$url_array = explode("/", $_SERVER['REQUEST_URI']);
# THE FIRST SPOT IN THE ARRAY CONTAINS THE ACTUAL WORD
# THE SLASHES HAVE ESSENTIALLY DISAPPEARED
echo $url_array[0];
Both methods produce the same output:
matthom :: blog
Gets trickier
This is fine for one level deep, ie: /blog/.
If your URI is /about-us/history/, you have another problem on your hands.
Maybe another entry will pop up in the future, addressing this issue.
Categories: PHP ![]()
Add Feedback (view all)
Leave feedback
matthom
is published and produced by Matt Thommes - an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from Chicago.
Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us.
Similar Entries
- RSS Best Practices? (8 recent visits)
- What are your RSS opinions? (3 recent visits)
- Nested TITLE attributes (1 recent visits)
- TITLE attribute for everything (5 recent visits)
- URI permalinks enhanced/explained (3 recent visits)
Stats
2 unique visits since August 2008
I'd just split on the slash like your second example (or "explode" as I guess PHP calls it), then loop through each element in the array. ti ... Read more.