mos*_*lak 3 php regex delimiter preg-split
我已经在这半天努力了,我似乎无法找到答案.请帮助一个菜鸟.:)
我有一个字符串,其中包含几个用大括号括起来的句子.它看起来像这样:
{Super duper extra text.} {令人敬畏的另一个文字!} {我们又来了......}
现在我想分开它.
我想我可以搜索像.} {等等的模式.所以我这样做:
$key = preg_split('/[!?.]{1,3}\} \{/',$key);
Run Code Online (Sandbox Code Playgroud)
但是这样我丢失了分隔符,我丢失了所有这些.!?在句末.
我试着这样做:
$key = preg_split('/([!?.]{1,3}\} \{)/',$key, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = array();
for ($i=0, $n=count($key)-1; $i<$n; $i+=2) {
$sentences[] = $key[$i].$key[$i+1]."<br><br>";
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码永远不会加载,所以我收集了一些错误.但是什么?
提前致谢.
你不需要拆分它,只需要调用preg_match()它.匹配的组将生成一个数组.内部分组的表达(),[^}]+所有字符相匹配,但不包括下一个}.您想要的输出值将在$matches[1]子数组中.
$input = "{Super duper extra text.} {Awesome another text!} {And here we go again...}";
$matches = array();
preg_match_all('/\{([^}]+)\}/', $input, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => {Super duper extra text.}
[1] => {Awesome another text!}
[2] => {And here we go again...}
)
[1] => Array
(
[0] => Super duper extra text.
[1] => Awesome another text!
[2] => And here we go again...
)
)
Run Code Online (Sandbox Code Playgroud)