如何匹配<;br>;如果前面什么都没有


How to match a <br> if nothing is infront

问题是,我在html_to_bcode函数中得到了更多我想要的换行符。

案例:我收到一条这样的随机短信。

test<br>
<br>
again something<br>

所以输出应该像

test
again somthing

不喜欢现在的

test

again some text
 `

我曾经做过

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

但是,如果之前有文本,它不应该用'n替换<br>,因为否则它只会进行

编辑案例和预期结果

解决方案就像@Dirk Horsten发布的:

$text2 = str_replace("<br />","<br>",$text);
$text = str_replace("<br>","",preg_replace("/^<br>/","'n",$text2));

我需要将代码中的<br />交换为<br>,否则会导致警告preg_replace():未知修饰符'>'

您的需求超出了字符串替换。我建议使用正则表达式。

如果要用单个''n:替换后续<br>

$text = $text = preg_replace("(/(<br>'s)+/m)","'n",$text);

如果你只想替换一行开头的<br>,试试这个

$text = $text = preg_replace("/^<br>/","'n",$text);

但随后线路内或线路末端的<br>仍然存在,因此可能需要

$text = $text = str_replace("<br>","",preg_replace("/^<br>/","'n",$text));

免责声明:我没有安装php,所以这不是测试。所以我把它做成了一个社区维基,所以任何人都可以编辑它

您几乎已经找到了解决方案。试试这个

<?php
$text="test<br>
<br>
again something<br>";
$text = str_replace("<br>","'n",$text);
echo nl2br($text);
?>

尝试以下代码,

$str = preg_replace_callback(
            '/[a-z]{1}<br>/',
            function ($matches) {
                return $matches[0].''n';
            }, $st);
 echo $str;