计算所有 <br /> 并将数字 4 替换为 php

我有这样的文字


"Hello, Hello, how are you?

Hello, Hello, how are you?<br />

Hello,

Hello,<br />

How are you?

How are you today?

I am fine; I am great

I am fine;<br />

I am just great

I am fine; I am great

I'm very well today!<br />

Great!

Hello, Hello, how are you?<br />

Hello, Hello, how are you?

Hello, Hello, How are you?<br />

How are you today?"

我需要将第四号替换<br />为<img>


如果只<br/>找到一个,则替换第一个


就一次


我尝试使用


function str_replace_first($from, $to, $subject)

{

    $from = '/'.preg_quote($from, '/').'/';


    return preg_replace($from, $to, $subject, 1);

}

但它只替换了找到的第一个


我尝试更换4号


阿波罗的战车
浏览 73回答 1
1回答

千万里不及你

尝试这个 :<?php$txt&nbsp; = "Hello, Hello, how are you?Hello, Hello, how are you?<br />Hello,Hello,<br />How are you?How are you today?I am fine; I am greatI am fine;<br />I am just greatI am fine; I am greatI'm very well today!<br />Great!Hello, Hello, how are you?<br />Hello, Hello, how are you?Hello, Hello, How are you?<br />How are you today?";$occurrences = substr_count($txt, '<br />');if( 1 === $occurrences ) {&nbsp; &nbsp; $txt = str_replace('<br />', "<img>", $txt);} else {&nbsp; &nbsp; $counter = 1;&nbsp; &nbsp; $txt = preg_replace_callback("/<br \/>/", function ($m) use (&$counter) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// replace 4th occurance&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if ($counter++ == 4) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "<img>";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return $m[0];&nbsp; &nbsp; }, $txt );}echo $txt;
打开App,查看更多内容
随时随地看视频慕课网APP