【问题标题】:replace multiple words that look the same in a string替换字符串中看起来相同的多个单词
【发布时间】:2018-01-24 12:02:30
【问题描述】:

我的 PHP 有点小问题。

$string = "[:string] has [:int] [:string] and [:int] [:string]";

我只想修改(可能用 str_replace)它:

$string = "He has 5 apples and 3 bananas";

我该怎么做?

(经典的 str_replace() 将用相同的单词修改所有 [:int],
这不是我想要的)。

非常感谢...

【问题讨论】:

  • preg_replace_callback
  • 你应该使用数组
  • 使用sprintf:sprintf('%s has %u %s and %u %s', 'He', 5, 'apples', 3, 'bananas');。 (可选)首先使用 str_replace 替换占位符:$format = str_replace(['[:string]', '[:int]'], ['%s', '%u'], $string)
  • 我不知道关键字在字符串中的位置。而且我不想显示字符串。

标签: php string replace str-replace keyword


【解决方案1】:

您可以使用以下正则表达式来捕获所有要替换的组,然后对其进行迭代。

\[:([^\]]+)\]

或者您可以只使用preg_replace_callback 并将所需的替换函数传递给它。

$data = [...];
preg_replace_callback('/\[:([^\]]+)\]/', $str, function (&$matches) use ($data) {
    return doSomethingWithMatches..
});

【讨论】:

  • 我不太明白。你能详细说明一下我的例子吗?
  • 我现在明白了。非常感谢你。有用的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2020-08-31
  • 2023-02-22
  • 1970-01-01
  • 2019-08-04
  • 2018-08-05
相关资源
最近更新 更多