0

I have a variable as shown below with upper case initials and a space. What would be ideal way to format so that it lower case the initials and puts "-" dash in between. So end result should be "los-angeles":

$city = "Los Angeles";

convert to

$city ="los-angeles";
3
  • are you trying to create a part of url? Commented Sep 24, 2009 at 16:32
  • Is that a How can I convert a document title into a URL slug? question? Commented Sep 24, 2009 at 16:32
  • not the document title though. Commented Sep 24, 2009 at 16:35

4 Answers 4

2

To accomplish your specific task, you'd do:

$city = str_replace(' ','-',strtolower($city));

But, if you're doing this so that the string will work in a URL (as the comments have suggested), you should do:

$city = urlencode($city);
Sign up to request clarification or add additional context in comments.

Comments

1
str_replace(' ', '-', strtolower($city));

But if you're trying to create url it won't be enough.

1 Comment

Mann i loveeee stackoverflow cant get better than this. Thanks for the reply
0
function slug($str)
{
    $str = strtolower(trim($str));
    $str = preg_replace('/[^a-z0-9-]/', '-', $str);
    $str = preg_replace('/-+/', "-", $str);
    return $str;
}

Assuming you're talking about PHP.

Comments

0
  /** method slugify
    * 
    * cleans up a string such as a page title
    * so it becomes a readable valid url
    *
    * @param STR a string
    * @return STR a url friendly slug
    **/

    function slugifyAlnum( $str ){

    $str = preg_replace('#[^0-9a-z]#i', ' ', $str );    // allow letter and numbers only
    $str = preg_replace('#( ){2,}#', ' ', $str );       // rm adjacent spaces

    return strtolower( str_replace( ' ', '-', $str ) ); // slugify


    }

Funny, I was working on this today, I trim it before sending it here, this func is for when Users are permitted to create a page title which you want to use to create a slug for mod_rewrite etc.

Allow for usual f-ups like more than one space, sticking non-alnum chars in it etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.