为什么我的PHP函数没有返回值?

时间:2014-04-09 09:24:27

标签: php

此函数用于清理给定值,但输出“n-a”,就好像没有指定值一样。它必须是最简单的问题,但就在这一刻它让我击败。

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 个答案:

答案 0 :(得分:2)

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

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

<强> Working Demo.

答案 1 :(得分:1)

  1. 尝试使用mb_string库而不是iconv。它是一个更好的图书馆。
  2. 在每个实例中尝试var_dump或echo以确保返回数据。
相关问题