【问题标题】:PHP explode string only if line does not end with '!'仅当行不以'!'结尾时,PHP才会爆炸字符串
【发布时间】:2010-11-16 11:04:42
【问题描述】:

我正在为 PHP 中的脚本编程语言编写解析器。该脚本语言的语法如下所示:

ZOMFG
&This is a comment
(show "Hello, World\!");

这是用该语言编写的页面,显示 Hello, World!在浏览器中。但我也可以有这样的代码:

ZOMFG
&This is a comment !
on multiple !
lines.
(show !
"Hello, !
World\!!
");

现在我使用explode("\n", $content) 将页面的内容分解为一个数组,该数组的每一行代码都位于一个单独的索引中。 所以

ZOMFG
&This is a comment
(show "Hello, World\!");

变成:

array('ZOMFG', '&This is a comment', '(show "Hello, World\!");');

当一行以 ! 结尾时(除非将 ! 转义为 \!),它应该将该行添加到数组中,包括以下行作为单个元素。所以

&This is a comment !
on multiple !
lines.

变成

&This is a comment on multiple lines.

有人知道怎么做吗?

【问题讨论】:

    标签: php parsing explode


    【解决方案1】:

    您应该能够使用 preg_split 进行否定的后视。

    (我正在寻找一个例子)

    $lines = preg_split('|(?<!\!)\n|', $code);
    

    根据 cmets,请注意这会导致换行符和 !保留。目前找不到比 str_replace 更简单的解决方案 - 但想象一下……!

    【讨论】:

    • 好主意,但这不会产生从连接线中剥离 !\n 组合的效果。
    • 感谢工作的人。一个问题:!仍然在行的中间。有谁知道如何解决这个问题?
    • str_replace('\!', "!", $line);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2014-08-29
    • 1970-01-01
    相关资源
    最近更新 更多