如何解决计算所有<br />并用php
我有类似的文字
"Hello,Hello,how are you?
Hello,how are you?<br />
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,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,$subject,1);
}
但仅替换找到的第一名
我尝试替换数字4
解决方法
尝试一下:
<?php
$txt = "Hello,Hello,how are you?
Hello,how are you?<br />
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,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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。