Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Regular Coder
    Join Date
    Oct 2009
    Posts
    438
    Thanks
    9
    Thanked 7 Times in 7 Posts

    Convert string into URL friendly string with PHP

    All,
    I'm trying to make a URL friendly string. So whatever the string is, I'm trying to make it lowercase and add a dash inbetween the characters. So it would look something like this:

    This is a test

    This would be converted to this-is-a-test

    How can I do that with PHP?

  • #2
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    try this;
    PHP Code:
    $String "This is a test";
    $String str_replace(" ""-"strtolower($String));
    echo 
    $String

  • Users who have thanked angst for this post:

    treeleaf20 (02-23-2012)

  • #3
    Regular Coder
    Join Date
    Oct 2009
    Posts
    438
    Thanks
    9
    Thanked 7 Times in 7 Posts
    That did the trick.
    Thanks

  • #4
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,542
    Thanks
    45
    Thanked 259 Times in 256 Posts
    You could also look at urlencode

  • #5
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    urlencode() wouldn't give him the result he asked for.

  • #6
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,542
    Thanks
    45
    Thanked 259 Times in 256 Posts
    Quote Originally Posted by angst View Post
    urlencode() wouldn't give him the result he asked for.
    Sorry, my response as poor.

    urlencode() will encode it into a format a URL can take. It won't be replacing spaces with dashes, but it accomplishes the same thing in a more standard format.

    If you specifically want to switch spaces with dashes, the above is the best method. But if you are looking for a standardized way of encoding a string for URL, urlencode() is the way to go.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •