首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从string - PHP中删除{{ }}中的内容

如何从string - PHP中删除{{ }}中的内容
EN

Stack Overflow用户
提问于 2013-06-11 14:19:14
回答 4查看 181关注 0票数 0

我有一个像这样的字符串

代码语言:javascript
复制
$data = "{{quickbar | image=Baby Beach Aruba.JPG | caption=Baby Beach | location=LocationAruba.png | flag=Flag of Aruba.svg | capital=Oranjestad | government=parliamentary democracy | currency=Aruban guilder/florin (AWG) | area=193 sq km | population=71,891 (July 2006 est.) | language=Dutch (official), Papiamento (a creole of Spanish, Portuguese, and Dutch origin), English (widely spoken), Spanish | religion=Roman Catholic 82%, Protestant 8%, Hindu, Muslim, Confucian, Jewish | electricity=120V/60Hz (North American plug) | callingcode=+297 | tld=.aw | timezone=UTC -4 }} Aruba [1] is a Caribbean island 15 miles north of the coast of Venezuela. The island is an autonomous dependency of the Kingdom of the Netherlands.";

我要删除{{}}中的所有内容以及该括号

我期望是这样的

代码语言:javascript
复制
$data = "Aruba [1] is a Caribbean island 15 miles north of the coast of Venezuela. The island is an autonomous dependency of the Kingdom of the Netherlands.";
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-06-11 14:21:17

如果这些括号不能嵌套,那就很简单了:

代码语言:javascript
复制
$result = preg_replace('/\{\{.*?\}\}\s*/s', '', $subject);

如果可以,您需要一个递归正则表达式:

代码语言:javascript
复制
$result = preg_replace('/\{\{(?:(?:(?!\{\{|\}\}).)*+|(?R))+\}\}\s*/', '', $subject);

说明:

代码语言:javascript
复制
{{          # Match {{
(?:         # Either match...
 (?:        # the following regex:
  (?!{{|}}) # Unless we're at the string {{ or }},
  .         # match any character
  )*+       # any number of times (possessively to avoid backtracking).
 |          # Or match...
 (?R)       # whatever this entire regex matches (recursively)
)+          # End of alternation, repeat as necessary
}}          # Match }}
\s*         # Match optional trailing whitespace

请在regex101.com上查看。

票数 6
EN

Stack Overflow用户

发布于 2013-06-11 14:25:34

代码语言:javascript
复制
<?php
$data = "this is {{ remove }} a {{ remove }} sample {{ remove }} text";
echo $data = preg_replace("/\{\{[^}]+\}\}/", "", $data); //this is a sample text
?>
票数 2
EN

Stack Overflow用户

发布于 2013-06-11 14:26:58

这应该是可行的

代码语言:javascript
复制
$data = "this is {{ remove }} a {{ remove }} sample {{ remove }} text";
echo preg_replace('/(\{\{)[^\{]*(\}\})/', '', $data);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17037653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档