How to Remove All Special Characters from Url?

I have my class

public function convert( $title )
    {
        $nameout = strtolower( $title );
        $nameout = str_replace(' ', '-', $nameout );
        $nameout = str_replace('.', '', $nameout);
        $nameout = str_replace('æ', 'ae', $nameout);
        $nameout = str_replace('ø', 'oe', $nameout);
        $nameout = str_replace('å', 'aa', $nameout);
        $nameout = str_replace('(', '', $nameout);
        $nameout = str_replace(')', '', $nameout);
        $nameout = preg_replace("[^a-z0-9-]", "", $nameout);    

        return $nameout;
    }

BUt I can't get it to work when I use special characters like ö and ü and other, can sombody help me here? I use PHP 5.3.

1

4 Answers

The first answer in this SO thread contains the code you need to do this.

1

And what about:

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>

From:

1

I wrote this function a while ago for a project I was working on and couldn't get RegEx to work. Its not the best way, but it works.

function safeURL($input){
    $input = strtolower($input);
    for($i = 0; $i < strlen($input); $i++){
        $working = ord(substr($input,$i,1));
        if(($working>=97)&&($working<=122)){
            //a-z
            $out = $out . chr($working);
        } elseif(($working>=48)&&($working<=57)){
            //0-9
            $out = $out . chr($working);
        } elseif($working==46){
            //.
            $out = $out . chr($working);
        } elseif($working==45){
            //-
            $out = $out . chr($working);
        }
    }
    return $out;
}
0

Here's a function to help with what you're doing, it's written in Czech: (and translated to English)

Here's another take on it (from the Symfony documentation):

<?php 
function slugify($text)
{
  // replace non letter or digits by -
  $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

  // trim
  $text = trim($text, '-');

  // transliterate
  if (function_exists('iconv'))
  {
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  }

  // lowercase
  $text = strtolower($text);

  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);

  if (empty($text))
  {
    return 'n-a';
  }

  return $text;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest