1

I want to make a hyphen separated string to use in the URL on the base of the user submitted title of the post. Suppose If user enter the title of the post as below

$title = "USA is going to deport indians -- Breaking News / News India";

I want to convert it as below

$url = "usa-is-going-to-deport-indians-breaking-news-news-india";

There could be some more characters that I also want to be converted. For Example '&' to 'and' and '#', '%', to hyphen(-). One of the way is to use the php replace function. But using this method, I have to call replace function so many times. It is time consuming. One more problem is there could be more than one hyphens (-) in the title string, I want to convert more than one hyphens (-) to one hyphen(-).

Is there any robust and efficient way to solve this problem?

Munib
  • 3,263
  • 8
  • 26
  • 35

2 Answers2

8

You can use preg_replace function to do this :

Input :

$string = "USA is going to deport indians -- Breaking News / News India";

$string = preg_replace("/[^\w]+/", "-", $string);
echo strtolower($string);

Output :

usa-is-going-to-deport-indians-breaking-news-news-india
Dead Man
  • 2,830
  • 22
  • 37
  • Thanks. But will it convert '&' to 'and' and '#', '%' to '-'. Please read my question fully. – Munib Apr 04 '13 at 09:31
1

I would suggest using the sanitize_title() function check the documentation

Divyang Desai
  • 7,055
  • 13
  • 45
  • 69
Lars
  • 11
  • 2