如何使用PHP将代码拆分为令牌?

时间:2016-05-27 13:15:20

标签: php split tokenize

我的字符串中的代码如下所示:

$code = "<html>
<body>
(if(foo == 10 || (foo == 20 && bar == 30))
    (foo(something)foo)
)if)
</body>
</html>";

如何分割字符串以获得结果:

array(
 "<html>\n<body>",
 "(if(",
 "foo == 10 || (foo == 20 && bar == 30))"
 "    ",
 "(foo(",
 "something",
 ")foo)",
 ")if)",
 "</body>\n</html>"
);
到目前为止,我有这个:

$tokens = preg_split("/(\(\w+\(|\)\w+\))/", $code, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo json_encode($tokens);

但作为回应,我得到了这个:

["\r\n\r\n\r\n","(if(","foo == 10 || (foo == 20 && bar == 30))\r\n ","(foo(","something",")foo)","\r\n",")if)","\r\n<\/body>\r\n<\/html>\r\n"]

<html><body>丢失,我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

该网页为html,<html><body>被解释为html,因此未显示。设置内容类型解决了问题:

header('Content-Type: text/plain');