删除特殊字符并在单词php mysql之间添加短划线

删除特殊字符并在单词php mysql之间添加短划线

问题描述:

I am trying to strip all special chars and add a dash between all the words.

Example:

Example text: How to make something, something else, and other stuff.

Example string:

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

Example of how it should look: How-to-make-something-something-else-and-other-stuff

I need a function that will strip all special chars but also add the dashes between every word "but also not adding dashes after the last word". Anyone have any ideas of how I should do this? I assume this is fairly simple. probably a preg_replace with regex which would solve the special char problem but adding the dashes is where I get confused and am not sure what to do.

我试图剥离所有特殊字符并在所有单词之间添加一个短划线。 p>

示例: p>

示例文本: 如何制作某些内容,其他内容以及其他内容。 p>

示例字符串: p>

  $ string =“如何制作某些内容,其他内容以及其他内容。”; 
  code>  pre> 
 
  

它应该如何显示的示例: 如何制作东西 - 其他东西和其他东西 p>

我需要一个能剥去所有特殊字符的函数但是 还要在每个单词之间添加短划线“但也不要在最后一个单词后添加短划线”。 任何人都有我应该怎么做的想法? 我认为这很简单。 可能是一个带有正则表达式的preg_replace,可以解决特殊字符问题,但添加破折号是我感到困惑的地方,不知道该怎么做。 p> div>

Assuming the string is in 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,'-');

After you've removed the non-alpha characters, you can explode() on spaces and then implode() with dashes.

I would explode the string at the spaces and then implode it with dashes like this:

$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;

this can be condensed obviously - but for simplicity these are the steps needed.