为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
阿波罗的战车 2023-10-21 15:55:15
我有这样的文字"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?"我需要将第四号替换<br />为<img>如果只<br/>找到一个,则替换第一个就一次我尝试使用function str_replace_first($from, $to, $subject){    $from = '/'.preg_quote($from, '/').'/';    return preg_replace($from, $to, $subject, 1);}但它只替换了找到的第一个我尝试更换4号
查看完整描述

1 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

尝试这个 :


<?php


$txt  = "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?";


$occurrences = substr_count($txt, '<br />');

if( 1 === $occurrences ) {

    $txt = str_replace('<br />', "<img>", $txt);

} else {

    $counter = 1;

    $txt = preg_replace_callback("/<br \/>/", function ($m) use (&$counter) {


         // replace 4th occurance

         if ($counter++ == 4) {

              return "<img>";

         }


         return $m[0];


    }, $txt );

}


echo $txt;


查看完整回答
反对 回复 2023-10-21
  • 1 回答
  • 0 关注
  • 72 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信