I am trying to remove extra characters from a title that the user types in to make it more URL-friendly. I am trying to use preg_replace() for it, but I keep getting errors. Here's my code:

$urlFriendlyTitle = preg_replace("/[/", "", $_POST['title']);
$urlFriendlyTitle .= preg_replace("/]/", "", $urlFriendlyTitle);
$urlFriendlyTitle .= preg_replace('/ /', '_', $urlFriendlyTitle);

When I remove the space it's fine, but trying to remove brackets just doesn't work. I haven't tried to remove Quotaion Marks or Slashes/ other characters yet(ex @, #, $, &, etc..), but hopefully I can figure that out once I fix the bracket problem.

    A fairly simple solution would be to convert any consecutive sequence of non-word characters or underscores into a single underscore:

    $urlFirendlyTitle = preg_replace('/[\W_]+/', '_', $_POST['title']);
    

      By the way, [man]rawurlencode/man and [man]urlencode/man are other ways to make user input URL friendly. As a bonus you do not actually alter the user input.

        NogDog wrote:

        A fairly simple solution would be to convert any consecutive sequence of non-word characters or underscores into a single underscore:

        $urlFirendlyTitle = preg_replace('/[\W_]+/', '_', $_POST['title']);
        

        What does that preg_replace() function actually replace from the string? I get so confused when it comes to that function, because the first parameter just doesn't make sense to me.

          \W is a character class that matches a non-word character. So, [\W] matches either a non-word character, or an underscore. Then [\W]+ matches one or more non-word characters and underscores.

            Write a Reply...