Home » PHP, Regular Expression

PHP: Simple and easy way to format URL string

22 April 2010 1,755 views Popularity: 4% Share/Bookmark

email

Here, I will be showing you a simple and easy one line code to format URL string with PHP. By URL string, I mean the url key in any Search Engine Friendly URL.

I have used preg_replace function to do so.

preg_replace($pattern, $replacement, $string)

preg_replace function performs a regular expression search and replace. This will search subject for matches to pattern and replaces them with replacement.

Here is my code:-

$urlKey = preg_replace(array('/[^a-z0-9-]/i', '/[ ]{2,}/', '/[ ]/'), array(' ', ' ', '-'), $string);

e.g. http://example.com/my-planet-earth/

I am talking about formatting ‘my-planet-earth’. Here, $string can be ‘My Planet Earth’ and the $urlKey will be ‘my-planet-earth’

$string = "planet+*&john doe / / \ \ ^ 44 5 % 6 + - @ ku ! ~ ` this";
$urlKey = preg_replace(array('/[^a-z0-9-]/i', '/[ ]{2,}/', '/[ ]/'), array(' ', ' ', '-'), $string);
// outputs: planet-john-doe-44-5-6---ku-this

Hope this helps.

Related posts:

  1. PHP: How to get integer or decimal from a string?
  2. jQuery: A simple Tooltip
  3. PHP: Parse Unparse String Array
  4. PHP: Generating Multiple Random String
  5. Random number, string generation in PHP
  6. jQuery: How to replace string, div content and image src?
  7. Javascript: How to get current URL without Query string?
  8. Regular Expression check, Validation in PHP
  9. jQuery: Print array and object
  10. Convert string to datetime and datetime to string in C#
  • http://abcphp.com/story/10862/ abcphp.com

    Simple and easy way to format URL string | Mukesh Chapagain’s Blog…

    Here, I will be showing you a simple and easy one line code to format URL string with PHP. By URL string, I mean the url key in any Search Engine Friendly…