【问题标题】:Get all occurrences of a similar string (which follows a pattern) within a text获取文本中所有出现的相似字符串(遵循模式)
【发布时间】:2014-09-29 13:35:07
【问题描述】:

我有一个巨大的文本,其中包含遵循模式的字符串:

{文本1} {文本2} ... {text10}

“文本”将保持不变,但后面的数字将始终递增。我无法预测它的最大值。

直到今天我都在使用这个:

preg_match_all("{text.}", $content, $occurrences);
foreach ($occurrences[0] as $occurrence){
    $content = str_replace("{" . $occurrence . "}", "test", $content);
}

直到今天,当我注意到如果我必须替换多个数字时 preg_match_all 规则不起作用时,一切都运行良好。这意味着它基本上会检测到“text2”,但不会检测到“text10”。

我应该如何更改此 preg_match 规则以检测“文本”之后的任何数字?

谢谢, 波格丹

【问题讨论】:

    标签: regex foreach str-replace preg-match-all


    【解决方案1】:
    preg_match_all("{text\d+}", $content, $occurrences);
    

    preg_match_all("{text.+}", $content, $occurrences);
    

    试试这个。 . 只匹配一个字符。这就是text2 匹配但text10 不匹配的原因,因为text 后面有2 个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2018-10-10
      • 1970-01-01
      相关资源
      最近更新 更多