如何使用PHP删除字符串中的重复字符?

I'am doing a project which is cleaning text with php. say that i have string like this :

$string = 'Life is like. . . . . . a box of chocolate. . . . . '; //each dot separated by space

How can i get the output like

$string ='Life is like a box of chocolate';

You can use preg_replace

$string = 'Life is like. . . . . . a box of chocolate. . . . . ';
echo preg_replace('/[.,]/', '', $string);

isn't it an easy str_replace()?

str_replace(". ", "", $text);

If your expected result is just to strip the dots and surrounding spaces, you can use preg_replace, but to get your expected result you need a bit more complex regex:

echo preg_replace(array("/(?<!\w) *\. */", "/(?<=\w)\. */"), array("", " "), $string);

Here I use an array of two regex to match two different cases:

  1. a dot followed and preceded by 0 or more spaces, all preceded by a character which is not a letter or a digit (\w in regex means a letter or a digit, and this is a negative lookbehind). This is substituted by an empty string.
  2. a dot followed by 0 or more spaces, and preceded by a letter or a digit. This is substituted by a space.

2 is to match and remove the dot in 'like. ' but leave a single space after the word.

This gives your expected result: 'Life is like a box of chocolate'

You can learn more on regex (short for regular expression) looking for tutorials on the web.