Your Ad Here

Posted By

evanwalsh on 02/11/08


Tagged

url php post slug convert explode


Versions (?)

Who likes this?

8 people have marked this snippet as a favorite

Abe
luman
maxav
Bron
pixelhandler
frara
nb109
pster


Make string into post slug


 / Published in: PHP
 

URL: http://nothingconcept.com

  1. <?php
  2.  
  3. function str2url($title,$sep = "-"){
  4. $exclude = array("!","@","#","$","%","^","&","*","(",")","=","{","}","[","]","|","\\","/","?","<",">","~","`","_","+","=","-");
  5. $pieces = explode(' ',str_replace($exclude,"",strtolower($title)));
  6. $output = NULL;
  7. foreach($pieces as $key => $val){
  8. if($pieces[$key+1] == NULL){
  9. $sep = NULL;
  10. }
  11. $output .= $val.$sep;
  12. }
  13. return $output;
  14. }
  15.  
  16. echo str2url("Evan Walsh Rocks"); // returns evan-walsh-rocks
  17.  
  18. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: tamriel on February 12, 2008

Why are you not just using PHP's "urlencode" function (php.net/rawurlencode or php.net/urlencode) ? I don't get the point of this snippet ...

Posted By: evanwalsh on February 13, 2008

This is to convert a string to be used as something like a permalink/post slug. Blog software (like Wordpress) does this. I just made this as a simple function one could use in one's own software.

Posted By: mohangk on September 8, 2008

This function is fine as long as you are handling cases where the slug returned is not unique separately

In the above case , $a and $b will be the same, yes ?

Posted By: mohangk on September 8, 2008

Sorry - what I was tring to say is for the string "Evan Walsh Rocks!" and "Evan Walsh Rocks?" you would get the same result.

Posted By: funkdaddy on May 15, 2009

This is simpler:

function str2url($title,$sep = "-"){ $output = strtolower($title); $output = pregreplace("/\s/",$sep,$output); return pregreplace("/[^a-z\d-]/",'',$output); }

Posted By: fendichen on October 7, 2010

hi friend, do you know cheap ghd, cheap mbt shoes, christian louboutin shoes hot sell online recently?

we are china wholesaler company, offer good quality nike dunks, ghd mk4, cheap soccer jerseys online, cheap jerseys online enjoy much discount.cheap nike dunks,nike shox why are you hestitate, welcome for retail, dropship, and wholesale orders.

You need to login to post a comment.