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?
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
I would suggest using the sanitize_title()
function check the documentation