Latest tutorial: Premium Flash Files | Ask Tutorial5! | Subscribe to RSS Register Login Find Hobbies
Advertisement
Do you need more help? You can now Ask Tutorial5! and get free support - Ask a question now!

Search engine friendly post slug URLs

(9 votes)
Written by DanielRo   
In this PHP tutorial you are going to learn how the famous post slugs are created and how you can create your own post-slug function for your web applications.

By default your publishing system (ie Wordpress) is creating URLs like http://example.com/?p=13. For Search Engine Optimization (SEO) sake one would prefer URLs like http://example.com/hello-world that would dramatically increase your odds of making a lot more sense to search engines (SE).

Here is an actual working example:

Post slug converter


Here's the actual code of the slug converter:

<?
function makeslug($title, $id, $ext=".html") {
$pslug = preg_replace("/[^a-zA-Z0-9 ]/", "", $title);
$pslug = str_replace(" ", "-", $pslug);
$pslug = strtolower($pslug);
$pslug = $id."_".$pslug.$ext;
return $pslug;
}
if(isset($_POST['title']) && isset($_POST['id'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$url = makeslug($title, $id);
echo "From <strong>" .$title. "</strong> our script created <strong>" .$url. "</strong><br /><br />";
echo "<a href=" .$url. ">".$title."</a><br /><br />";
echo "Notice the generated URL of the above link.";
}
else {
?>
<strong>Post slug converter</strong><br />
<form action=<?=$_SERVER['PHP_SELF'];?> method=post name="conv">
<input type="text" name="title" value="Enter title to convert" onfocus="if (this.value == 'Enter title to convert') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter title to convert';}" ><br /><br />
<input type="text" name="id" value="Enter ID" onfocus="if (this.value == 'Enter ID') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter ID';}" /><br />
<input type=submit name="conv" value="Convert">
</form>
<? } ?>


By reading our PHP Forms and Input form text switch using JavaScript tutorials, you will get a general ideea of the techniques used here.

The new PHP code we are using is the makeslug function. This is a basic user defined php function with two required parameters ($title and $id) and an optional parameter $ext.

By using PHP's preg_replace this function removes any non a-zA-Z0-9 characters from our string. Then by using str_replace, it replaces all white spaces with a dash "-".
Then by using strtolower it converts all of our strings characters to lowercase and then returns our final converted string (post slug, friendlyurl).


Subscribe now via RSS feed and get all the new tutorials

written by Geoserv , February 27, 2008

Great tutorial.

STUMBLED!

DOTTED:
http://www.newsdots.com/tutorials/online-training-and-tutorials/

Do you need more help? Ask now!
 

busy
Last Updated ( Monday, 22 October 2007 )