【问题标题】: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} )