Pass and $_GET a Title in PHP

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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

John Hartley is a Director of Product Engineering at Beam Dental in Columbus, OH. With 5+ years of leadership experience he has worked in startups, agencies, and began his career as a freelance Front End Developer. Always looking to iterate, this blog is a place for him to share his knowledge as well as hone his craft, challenge assumptions, and build a strong base of leadership and management knowledge. Connect with him on LinkedIn

0
Would love your thoughts, please comment.x
()
x