php 从php中的字符串替换br标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5849130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:40:36  来源:igfitidea点击:

replace br tag from a string in php

phpregex

提问by Renjith R

I have the following string. I want to replace the line break with /n

我有以下字符串。我想用 /n 替换换行符

Good FRIENDS are hard to find,<br
            /> harder to leave,<br
            /> and impossible to forget.

回答by hsz

preg_replace("/<br\W*?\/>/", "\n", $your_string);

回答by JD Isaacks

Have you tried str_replace?

你试过str_replace吗?

str_replace("<br />", "\n", $your_string);

回答by Thilo

Use str_replace

使用str_replace

$text = str_replace("<br />", "\n", $text);

If there is actually a line break within the <br />tag as in your sample code, try this:

如果<br />您的示例代码中的标签中确实有换行符,请尝试以下操作:

$text = preg_replace("/<br\n\W*\/>/", "\n", $text);

回答by Mehdi Ajdari

Use This function

使用此功能

   function separate( $str,$subStr, $count )
  {
     $formatStr = '';
     $start=0;
     $num = 1;
     while(!(strpos($str,$subStr,$start) === null))
     { 
       $first = strpos($str,$subStr,$start);
       if ($first < $start)
          break; 
       $newStr = substr($str,$start,$first - $start + 1 );
       $formatStr .= $newStr;
       if ($num % $count == 0)
          $formatStr .= '<br>';
       $num ++;
       $start = $first +1;
     }
     return $formatStr;
  }

Example

例子

$str = 'AAA.BBB.CCC.DDD.EEE.FFF.CCC';
echo separate ($str,'.', 3);

Output

输出

AAA.BBB.CCC.
DDD.EEE.FFF.

回答by Anup Khandelwal

You can also try below regex:

您也可以尝试以下正则表达式:

$string = preg_replace( '@^(<br\b[^>]*/?>)+@i', '', $string );