【问题标题】:preg replace find keywordpreg 替换 find 关键字
【发布时间】:2016-03-08 21:34:57
【问题描述】:

非常简单的 preg 替换,但我想不通。

我需要搜索关键字,例如:{this_is_a_key} 并替换为其他内容。

$text = 'this is a sentence with a {this_is_a_key} in it';
echo preg_replace('/\{\w{1}\}/i','keyword',$text);
//output should be
//## "this is a sentence with a keyword in it" ##//

到目前为止,这对我不起作用,我尝试了 ()[] 的组合,但没有运气

【问题讨论】:

标签: php regex preg-replace


【解决方案1】:

\w{1} 表示一个“单词字符”。请改用\w+[^\}]+

另外,当使用\w 时,不需要i 修饰符。

【讨论】:

  • 我正在寻找我需要使用 str_replace 代替的常量替换器,如stackoverflow.com/questions/3372735/… 中所述
  • mvds 给出了很好的答案。只需使用 '{this_is_a_key}' 作为替换数组中的键。这就是他所说的对读者锻炼的意思。
猜你喜欢
  • 2017-01-05
  • 1970-01-01
  • 2016-04-19
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多