Pass and $_GET a Title in PHP

Posted on: August 1st, 2012

Passing a variable in a URL is fairly common in the web world. It’s good for ad targeting and passing keywords to the file being opened. Say for example you want to send a web page fan-letter to Chuck Norris and Mr. T, but are so lazy that you only write one letter. You wouldn’t want to hard code “Dear Chuck Norris” into the beginning of your letter, or Mr. T would be pity your foolishness.

To prevent Mr. T from putting the hurt on you with his perfectly formed mohawk (possible a mohawk wig these days), you can use the following PHP in your fan letter page.

<?php
  $passed = $_GET['title']; //pulls in ?title=Chuck_Norris

So the above snippet will return $passed = ‘Chuck_Norris’, but do you really want that underscore in there? Chuck Norris’ beard says no. So, take a look at this next bit.

  $title = str_replace("_"," ",$passed);
?>

<h1><?php echo $title; ?></h1>

Easy enough right? Take the variable that’s holding Chuck_Norris and toss it through a string replace where we replace underscores with spaces and boom $title now equals ‘Chuck Norris’ and we can keep our letter the same without getting beat up.

The only thing that changes is what comes after ‘?title=’ go ahead and put your own name in and come to my birthday party. Actually don’t, Liam Neeson might be there and he has a history of acquaintances being Taken.

As in all things PHP, this is not the ONLY way to do this, but it is the way I favor. Let me know what you think and what you use this for.

Tags: , , , , , ,

previous post: Fatal Errorz next post: Sublime Text 2 Tutorial – Find and Replace