1

Hi first time dealing with preg_replace and found damn complex to understand specially learner.

Trying to change title string to slug for url structure where it remove all special character like ( ) ? * and replace multiple space into single - with converting all text in to lower case.

Here is my funny code but not getting desire output.

$title_slug = $q_slug->title;
$title_slug = preg_replace("/[\s+\?]/", " ", $title_slug);        
$title_slug = str_replace("  ", " ", $title_slug);
$title_slug = str_replace(" ", "-", $title_slug);
$title_slug = preg_replace("/[^\w^\_]/"," ",$title_slug);
$title_slug = preg_replace("/\s+/", "-", $title_slug);
$title_slug = strtolower($title_slug);

return $title_slug;

EDIT: Added Example

Example: if my title is what is * the() wonder_ful not good?? and where??? Result: if-my-title-is-what-is-the-wonder_ful-not-good-and-where

Feel free to laugh :) and million thanks for help.

Code Lover
  • 8,099
  • 20
  • 84
  • 154

3 Answers3

3

Check out this tutorial for a clean URL generator, or even use this existing SO solution which eschews regular expressions altogether. This will probably get the job done:

function toAscii($str) {
   $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
   $clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean);
   $clean = strtolower(trim($clean, '-'));
   return preg_replace("/[\/_| -]+/", '-', $clean);
}
Community
  • 1
  • 1
hohner
  • 11,498
  • 8
  • 49
  • 84
  • I was already on Google to search for this type of answer! iconv() is a great helper for this kind of tasks! – powtac Jan 27 '13 at 18:55
  • @powtac its really happy to being on stackoverflow. people are amazing and having great experience and expertise and always ready to help. – Code Lover Jan 27 '13 at 18:57
  • Your answer is good one only one thing, it's removing `_` which I want. However now I am really confuse which answer is the best to choose all are working fine but Salman A answer is perfect what I need – Code Lover Jan 27 '13 at 19:03
2

Here's a nice function to do just that:

function toSlug ($string) {
        $string = strtolower($string);
        // Strip any unwanted characters
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        // Clean multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        // Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);

        return $string;
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

Try this:

$string = strtolower($string);
$string = preg_replace("/\W+/", "-", $string); // \W = any "non-word" character
$string = trim($string, "-");
Salman A
  • 262,204
  • 82
  • 430
  • 521