【问题标题】:Extract strings from another string beginning and ending with a special char [closed]从另一个以特殊字符开头和结尾的字符串中提取字符串[关闭]
【发布时间】:2016-12-21 19:09:17
【问题描述】:

假设我有一个类似

的字符串

这{是}一个来自我的新 {test} {string}。

我的目的是将{} 包围的所有字符串放在一个数组或一个列表中。 所以我想得到:

{is} {test} {string}

子字符串在这里不起作用。可能“正则表达式”是解决方案,但我无法让它为我工作。有人可以帮忙吗?

【问题讨论】:

  • 什么你试过了吗?
  • 向我们展示您的代码。

标签: php regex string split substring


【解决方案1】:

您想使用正则表达式。在这种情况下,您需要使用以下正则表达式:

/\{[^}]*\}/

这是什么意思?

  • / = 正则表达式的开始
  • \{ = 匹配字符 {
  • [^}] = 匹配除}以外的任何字符...
  • * = ... 1 到无限次
  • \} = 匹配字符 }
  • / = 正则表达式结束

你可以这样使用:

$re = "/\{[^}]*}/";
$str = "This {is} a new {test} {string} from me."; 

preg_match_all($re, $str, $matches);

print_r($matches[0]);

其中$matches[0] 是一个匹配数组。这将输出:

数组 ( [0] => {is} [1] => {test} [2] => {string} )

【讨论】:

  • 你救了我的命,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
相关资源
最近更新 更多