问题描述
我正在尝试做一些必须非常简单的事情,但是我对PHP还是陌生的,因此我为此而苦苦挣扎。我想要的是拆分一个包含0、1个或多个定界符(大括号)的字符串,同时将定界符AND字符串与AND字符串之间的字符串保持在外面。
I'm trying to do something that must be really simple, but I'm fairly new to PHP and I'm struggling with this one. What I want is to split a string containing 0, 1 or more delimiters (braces), while keeping the delimiters AND the string between AND the string outside.
ex:'您好{F} {N},您好吗?'将输出:
ex: 'Hello {F}{N}, how are you?' would output :
Array ( [0] => Hello
[1] => {F}
[2] => {N}
[3] => , how are you? )
到目前为止,这是我的代码:
Here's my code so far:
$value = 'Hello {F}{N}, how are you?';
$array= preg_split('/[\{\}]/', $value,-1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($array);
输出(缺少括号):
Array ( [0] => Hello
[1] => F
[2] => N
[3] => , how are you? )
我也尝试过:
preg_match_all('/\{[^}]+\}/', $myValue, $array);
哪个输出(大括号在那里,但外面的文本被刷新了):
Which outputs (braces are there, but the text outside is flushed) :
Array ( [0] => {F}
[1] => {N} )
我敢肯定我在使用preg_split时使用的是正则表达式,但是使用了错误的正则表达式。谁能帮我这个?还是告诉我是否要离开?
I'm pretty sure I'm on the good track with preg_split, but with the wrong regex. Can anyone help me with this? Or tell me if I'm way off?
推荐答案
您没有捕获定界符。将它们添加到捕获组:
You aren't capturing the delimiters. Add them to a capturing group:
/(\{.*?\})/
这篇关于拆分字符串,同时将定界符和字符串保留在外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!