Split a string while keeping delimiters and string outside

落爺英雄遲暮 提交于 2019-12-24 06:42:34

问题


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: '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);

which outputs (missing braces) :

Array ( [0] => Hello 
        [1] => F
        [2] => N 
        [3] => , how are you? )

I also tried :

preg_match_all('/\{[^}]+\}/', $myValue, $array);

Which outputs (braces are there, but the text outside is flushed) :

Array ( [0] => {F} 
        [1] => {N} ) 

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?


回答1:


You aren't capturing the delimiters. Add them to a capturing group:

/(\{.*?\})/



回答2:


You need parentheses around the part of the expression to be captured:

preg_split('/(\{[^}]+\})/', $myValue, -1, PREG_SPLIT_DELIM_CAPTURE);

See the documentation for preg_split().



来源:https://stackoverflow.com/questions/16006590/split-a-string-while-keeping-delimiters-and-string-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!