【问题标题】:Replacing text using a loop in PHP在 PHP 中使用循环替换文本
【发布时间】:2014-11-13 11:20:33
【问题描述】:

我正在尝试遍历每个 [footnote] 并将其替换为一些 HTML。以下是一些示例文本:

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

并使用 preg_match_all 创建计数:

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

然后我将此计数用作循环,以查找文本并将其替换为适当的 HTML:

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

但是,之后,当我echo $new_content; 每个[footnote] 有相同的数字时,2

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

有人知道为什么这个数字没有增加吗?这就是我想要的

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

【问题讨论】:

标签: php preg-match


【解决方案1】:

你可以这样做

$i = 0;
preg_replace_callback('/[footnote]/', 'replaces_counter', $content);

function replaces_counter($matches) {
  global $i;
  return "<span class='footnote'>".$i++."</span>";
}

【讨论】:

  • $matches 参数在这里有什么作用?
【解决方案2】:

str_replace 一次替换所有内容,您需要支持$limitpreg_replace(=要进行的替换次数):

$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;

请注意,第 5 个参数 $count 使您的计数代码变得多余 - 我们只是不断替换,直到无法再进行替换为止。

【讨论】:

  • 谢谢,两边的~ 是干什么用的?
  • @tmyie:正则表达式语法。
【解决方案3】:

由于您尝试替换文字字符串,因此可以避免使用正则表达式。示例:

$str = 'Hello [footnote], how are you [footnote], what are you up to [footnote]?';

$arr = explode('[footnote]', $str);
$count = 1;

$result = array_reduce($arr, function ($carry, $item) use (&$count) {
     return (isset($carry)) 
         ? $carry . '<span class="footnote">' . $count++ . '</span>' . $item
         : $item;   
});

print_r($result);

【讨论】:

    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2021-07-28
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多