php - 我如何分解(拆分)给定的文本和分隔符字符串?
问题描述
我如何解析由两个块形成的字符串:
{ text }
text
对于这两种情况,我都有两个正则表达式:
\{[^\}]+\}
*.
但不理解将它组合在一个正则表达式中。我曾考虑使用 or ( |
) 运算符这样做:
/(\{[^\}]+\}|.*)/
但它不起作用。我该如何解决?
具体来说,如果我有一个字符串:
"{this is first text} this is second text {this is third text}"
使用preg_match_all
我想要的东西:
Array
(
[0] => Array
(
[0] => {this is first text}
[1] => this is second text
[2] => {this is third text}
)
)
但我有结果:
Array
(
[0] => Array
(
[0] => {this is first text}
[1] => this is second text {this is third text}
[2] =>
)
)
非常感谢您的帮助。
解决方案
试试这个:
$str = "{this is first text} this is second text {} this is third text";
preg_match_all('/\s*(?:{})*\s*({.+?}|[^{}]+)/', $str, $matches);
print_r($matches[1]);
'/\s*(?:{})*\s*({.+?}|[^{}]+)/'
意味着跳过空格和空大括号并在其中插入{}
(里面也包括花括号)或除符号{
和之外的所有内容}
。
推荐阅读
- javascript - 我们可以从异步函数中调用非异步函数吗?
- python - VUE axios get API not found
- android - 检查 Playstore 中的内部测试人员是否已安装该应用程序
- excel - ActiveSheet.ShowAllData 在 2 台机器上返回不同的结果
- sql - 如何获取关系中所有ID的所有连续间隔
- c# - 如何将凭据分配给 WebRequest 然后导航到它?
- php - 如何在 php 7.2 中使用最新版本的 mpdf 和 codeignator
- php - Laravel 5.8 同步/附加/分离事件
- c# - 复制大量文件的最快方法
- javascript - 在 div 事件期间来回更改文本