shaytac
shaytac

Reputation: 4004

PHP Format variable

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";

Upvotes: 0

Views: 202

Answers (4)

Cups
Cups

Reputation: 6896

  /** 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

Upvotes: 0

brettkelly
brettkelly

Reputation: 28205

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);

Upvotes: 2

Deniz Dogan
Deniz Dogan

Reputation: 26217

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.

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319531

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

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

Upvotes: 1

Related Questions