2014-04-09 88 views
0

此函数旨在清理给定的值,但是它会输出“n-a”,就好像没有指定值一样。它必须是最简单的问题,但是现在这个问题让我感到沮丧。为什么我的PHP函数没有返回值?

function slug($text){ 

    // replace non letter or digits by - 
    $text = preg_replace('~[^pLd]+~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; 
} 

我很感激一些输入。

+2

** **哪里它变空?您是否尝试过倾销变量? (在替换之后,在修剪之后,在strtolower之后,在第二次替换之后) – h2ooooooo

+0

'$ text = preg_replace('〜[^ - w] +〜','',$ text);''这除了'-'和' w'。我认为你的字符串没有'-'或'w'。所以你得到空字符串。尝试在这里重写正则表达式 – krishna

回答

1
  1. 尝试使用mb_string库而不是iconv。它是一个更好的库。
  2. 在每个实例中,尝试使用var_dump或echo来确保数据的返回。
2

你需要改变这似乎是不正确的正则表达式第一,应该是,

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

Working Demo.

+1

我认为他的意思是'\ pL \ d'(aka。unicode letter/digit)。 – h2ooooooo

+0

@ h2ooooooo - 同意。 – Rikesh

+0

@ h2ooooooo - 添加反斜杠解决了我的问题,即第一个正则表达式为\ pL \ d,第二个正则表达式为\ w – TimD