【问题标题】:PHP Code to replace special characters in string removes the charactersPHP代码替换字符串中的特殊字符删除字符
【发布时间】:2016-11-30 07:58:47
【问题描述】:

这个用于创建 URL slugs 的函数:

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

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

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

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

  // remove duplicate -
  $text = preg_replace('~-+~', '-', $text);

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

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

  return $text;
}

不替换如下字符:

ľščťýžťžýéíáý

类似于:

lsctyztzyeiay

但是,它会完全删除它们

所以这个字符串:

asdf 1234 3 ľščťlkiop

变成

asdf-1234-3-lkiop

代替:

asdf-1234-3-lsctlkiop

知道是什么导致非英文字符消失以及如何使它们转换为英文变体吗?

【问题讨论】:

标签: php url replace


【解决方案1】:

我测试了你的函数,它似乎工作正常。
You can check here 输出你的数据。

【讨论】:

  • 不工作。如果我做 var_dump 我得到这个:ÄšťľšÄťľšÄťľšÄÅ¥ 知道为什么吗?
  • 您必须将网页的编码设置为 UTF-8 才能正确显示特殊的非 ASCII 字符。在您网页的<head> 块中添加<meta charset="UTF-8">
  • 你是对的,它在视图中工作,但是当保存到数据库时它被搞砸了。在保存到数据库之前,我会检查一些 htmlentities 或其他内容。谢谢。
  • 阅读此文,会有所帮助:How to support UTF-8 completely in a web application
猜你喜欢
  • 2017-03-24
  • 2011-04-29
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多