dongpeng8994 2013-10-28 18:23
浏览 57

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

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);
  • 写回答

2条回答 默认 最新

  • douhang5460 2013-10-28 18:32
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了