dpxyfa4718 2014-11-13 11:20
浏览 105

使用PHP中的循环替换文本

I am trying to loop through every [footnote] and replace it with some HTML. Here is some sample text:

Hello [footnote], how are you [footnote], what are you up to [footnote]?

And using preg_match_all to create a count:

$match_count = preg_match_all("/\[footnote]/", $content);

I then use this count as a loop, to find and replace the text with appropriate HTML:

for ($i=0; $i < $match_count; $i++) { 
   $new_content = str_replace('[footnote]', "<span class='footnote'>$i</span>", $content);
}

However, after, when I echo $new_content; each [footnote] has the same number, 2:

<span class="footnote">2</span>
<span class="footnote">2</span>
<span class="footnote">2</span>

Would anyone know why this number is not incrementing? This is what I want

<span class="footnote">1</span>
<span class="footnote">2</span>
<span class="footnote">3</span>
  • 写回答

3条回答 默认 最新

  • dpbe81245 2014-11-13 11:35
    关注

    str_replace replaces everything at once, you need preg_replace which supports $limit (=number of replacements to make):

    $content = "Hello [footnote], how are you [footnote], what are you up to [footnote]?";
    
    $i = 0;
    do {
        $i++;
        $content = preg_replace('~\[footnote\]~', "<span>$i</span>", $content, 1, $count);
    } while($count);
    
    print $content;
    

    Note that the 5th parameter, $count makes your counting code superfluous - we just keep replacing until no more replacement could be made.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100