【问题标题】:removing special chars and adding a dash between words php mysql删除特殊字符并在单词 php mysql 之间添加破折号
【发布时间】:2011-03-30 00:08:24
【问题描述】:

我正在尝试去除所有特殊字符并在所有单词之间添加一个破折号。

例子:

示例文本: 如何制作一些东西、其他东西和其他东西。

示例字符串:

$string = "How to make something, something else, and other stuff.";

外观示例: 如何制作其他东西和其他东西

我需要一个函数来去除所有特殊字符,同时在每个单词之间添加破折号“但也不在最后一个单词之后添加破折号”。有人对我应该如何做有任何想法吗?我认为这相当简单。可能是带有正则表达式的 preg_replace 可以解决特殊字符问题,但添加破折号是我感到困惑并且不知道该怎么做的地方。

【问题讨论】:

  • 如何定义“特殊字符”?非字母数字字符?或者除了 a-z 之外的任何东西?

标签: php mysql


【解决方案1】:

假设字符串是 utf-8 格式:

$string = 'Höw to máke sòmething, something else, and other stuff';
$string = preg_replace('/[^a-z0-9]+/i','-',
   iconv('UTF-8','ASCII//TRANSLIT',$string));
$string = trim($string,'-');

【讨论】:

  • 问题在于它在最后一个单词之后添加了一个破折号。否则就可以了。
  • 啊,好吧,如果你不想这样,我会编辑它...它只是最后的 .- 取代 :)
  • 酷似乎工作得很好。如果允许,我会在 6 分钟内接受您的回答。谢谢。
【解决方案2】:

删除非字母字符后,您可以在空格上explode(),然后用破折号implode()

【讨论】:

  • 这是个好主意,但 Wrikken 的回答更多的是我想要的。感谢您的建议,非常感谢。
【解决方案3】:

我会在空格处爆炸字符串,然后用这样的破折号将其内爆:

$string = trim($string); // removes white space from ends
$string = preg_replace("/[^A-Za-z0-9]/","",$string); // removes special chars 
$string = explode(' ', $string); // separates the words where there are spaces
$string = implode('-', $string); // puts the words back into a sentence separated by dashes
echo $string;

这显然可以被压缩 - 但为简单起见,这些是所需的步骤。

【讨论】:

    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多