PHP清理功能无法正常工作

时间:2010-09-30 10:40:23

标签: php

我在PHP中为一个项目创建了一个干净的函数,以帮助从数据库内容构建有用的URL。它会删除任何空格和特殊字符,因此像“MyMotörheadAlbums”这样的句子会出现在URL my-motoerhead-album中。然而,它似乎没有正确转换ö,ä,ü等变音符号,我无法弄清楚为什么。

以下是代码:

function clean($text) {
$text = trim($text);
$text = strtolower($text);
$code_entities_match = array(
' ',    '--',    '"',    '!',    '@',    '#',    '$',    '%',    '^',    '&',
'*',    '(',    ')',    '_',    '+',    '{',    '}',    '|',    ':',    '"',    
'<',    '>',    '?',    '[',    ']',    '\\',    ';',    "'",    ',',    '.',
'/',    '*',    '+',    '~',    '`',    '=',    '¡',    '¿',     '´', '%C2%B4', 
'ä',    'ö',    'ü',    'ß',    'å',    'á',    'à',
'ó',    'ò',    'ú',    'ù',    'í',    'é',    'è',    'ø', 'Þ', 'ð', '%C3%9E', '&thorn;'
);
$code_entities_replace = array(
'',    '-',    '',    '',    '',    '',    '', '',    '',    '',    
'',    '',    '',    '',    '',    '',    '',    '',    '',    '',
'',    '',    '',    '',    '',    '',    '',    '',    '',    '',    
'',    '',    '',    '',    '',    '',    '',    '',    '',    '',    
'ae',    'oe',    'ue',    'ss',    'aa',    'a',    'a',    'o',    'o',    'u',    'u',    'i',    'e',    'e',    'oe',    'th',    'th',    'th',    'th'
);
$text = str_replace($code_entities_match, $code_entities_replace, $text);
return $text;

}

1 个答案:

答案 0 :(得分:0)

这是我用来构建url-safe字符串的函数:

static public function slugify($text)
{ 
  $text = str_replace(" ", "_", $text);

  // replace non letter or digits by -
  $text = preg_replace('~[^\\pL\d_]+~u', '-', $text);

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

  // transliterate
  $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;
}

它来自symfony的Jobeet教程。