用单个替换连续出现的字符串

In short change contineous occurance of the string value that we specify, with a single string value. ie

hello \t\t\t\t\t world \t\t\t

to

hello \t world \t

In detail


\tExample

to 
understand

 the current
 situatuion\t\t\t\t\t.

i wanted the output as

 Example
to 
understand
 the current
 situation .

output in html

<br /> Example<br />to <br />understand<br /> the current<br /> situation .

and i managed to get this output

Example

to 
understand

the current
situatuion .

with this code

$str='
\tExample

to 
understand

 the current
 situatuion\t\t\t\t\t.';


 echo str_replace(array('
', '','\t','<br /><br />' ),
            array('<br />', '<br />',' ','<br />'), 
            $str);

If you know the subset of characters you want to replace, such as , and \t, a single regex should do the trick to replace all repeating instances of them with the same:

/(
|
|\t)\1+/

You can use that with PHP's preg_replace() to get the replacement effect:

$str = preg_replace('/(
|
|\t)\1+/', '$1', $str);

Then, to make the output "HTML friendly", you can make another pass with either nl2br() or str_replace() (or both):

// convert all newlines (
, 
) to <br /> tags
$str = nl2br($str);

// convert all tabs and spaces to &nbsp;
$str = str_replace(array("\t", ' '), '&nbsp;', $str);

As a note, you can substitute the | |\t in the above regex with \s to replace "all whitespace" (including regular spaces); I wrote it out specifically because you didn't mention regular spaces and in case you wanted to add additional characters to the list to replace.

EDIT Updated the \t replacement above to replace with a single-space instead of 4-spaces per a comment-clarification.

You can try this alternative.

$string = "
\tExample

to 
understand

 the current
 situation\t\t\t\t\t.";

$replacement = preg_replace("/(\t)+/s", "$1", $string);

$replacement = preg_replace("/(
|
)+/s", '<br />', $string);

echo "$replacement";

#<br /> Example<br />to <br />understand<br /> the current<br /> situation

.