亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算所有 <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 關注
  • 99 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號