在laravel blade中使用nl2br将url替换为锚点标签



你好,我有laravel刀片,这是出现问题的部分

@php
$reg_exUrl = "/(http|https|ftp|ftps)://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/S*)?/";
@endphp
<div class="message"> 
@php
$text = nl2br(e($message));
@endphp
@if(preg_match($reg_exUrl, $text, $url)){!! preg_replace($reg_exUrl, '<a href="$0" target="_blank">$0</a> ', $text) !!}
@else {!!$text!!}
@endif
</div>

如果链接只在文本中,但其中夹杂了一些单词和换行符,则效果良好像这个消息

你好,亲爱的买家

链接运行良好https://google.com/blabla

和一些随机文本

它转换成这个html代码

hello dear buyer<br>
<br>
the link is working good<br>
<a href="https://google.com/blabla<br" target="_blank">https://google.com/blabla<br< a="">  /&gt;
<br>
and some random text<br>
<br>

如何修复这个

如果用户输入包含行的消息,我想将url替换为锚标记并显示换行符

还可以使用刀片中的e((函数来防止任何html代码运行

有人帮忙吗

嗯,如果<br>标记之前只有一个空格,那么您的代码就可以工作了。我认为您不能这样做,因为
已绑定到链接。也许您现在可以这样做(直到其他人有更好的解决方案(,并确保在str_replace:之后调用e()

$message = str_replace('<br>', ' <br>', $message);
// Optional to trim double spaces
$message = preg_replace('/ss+/', ' ', $message);

最新更新