dongpo1599 2018-11-06 10:22
浏览 9
已采纳

文本中的多个短代码

I have the following text

this is line one

[gallery]

this is line two

[gallery]

this is line three

I also have the following code in php

$text = 'this is line one [gallery] this is line two [gallery] this is line three';
$gallery = array('gallery name1', 'gallery name2');

foreach ($gallery as $key => $val) {
    $text = preg_replace('#\[gallery\]#si', $val, $text); 
}

I want to replace the first [gallery] with the first value of array $gallery and the second [gallery] with the second value of array $gallery.

How can i do this?

  • 写回答

1条回答 默认 最新

  • dongqiang4819 2018-11-06 10:38
    关注

    You need to add a limit so that only 1 entry gets changed:

    $text = preg_replace('#\[gallery\]#si', $val, $text, 1); 
                                                         ^ add a limit
    

    Now, on each iteration, 1 instance of [gallery] will get replaced.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?