【发布时间】:2018-02-12 01:54:01
【问题描述】:
我有这个函数,它利用 preg_replace_callback 将一个句子分成属于不同类别(字母、汉字、其他所有字符)的块的“链”。
该函数正在尝试将字符 ' 、 { 和 } 包含为“字母”
function String_SplitSentence($string)
{
$res = array();
preg_replace_callback("~\b(?<han>\p{Han}+)\b|\b(?<alpha>[a-zA-Z0-9{}']+)\b|(?<other>[^\p{Han}A-Za-z0-9\s]+)~su",
function($m) use (&$res)
{
if (!empty($m["han"]))
{
$t = array("type" => "han", "text" => $m["han"]);
array_push($res,$t);
}
else if (!empty($m["alpha"]))
{
$t = array("type" => "alpha", "text" => $m["alpha"]);
array_push($res, $t);
}
else if (!empty($m["other"]))
{
$t = array("type" => "other", "text" => $m["other"]);
array_push($res, $t);
}
},
$string);
return $res;
}
但是,花括号似乎有问题。
print_r(String_SplitSentence("Many cats{1}, several rats{2}"));
从输出中可以看出,该函数将 { 视为字母字符,如所示,但在 } 处停止并将其视为“其他”。
Array
(
[0] => Array
(
[type] => alpha
[text] => Many
)
[1] => Array
(
[type] => alpha
[text] => cats{1
)
[2] => Array
(
[type] => other
[text] => },
)
[3] => Array
(
[type] => alpha
[text] => several
)
[4] => Array
(
[type] => alpha
[text] => rats{2
)
[5] => Array
(
[type] => other
[text] => }
)
我做错了什么?
【问题讨论】:
-
我无法复制您的问题。在 3v4l 中运行您的代码会发现您的正则表达式 works as expected。
-
字符类拼写错误?
a-zA-Z0-9}'?您的字母字符类中有},但没有{。那是猴子扳手吗?你的模式中没有.,所以s标志是不必要的。你运行的是什么 php 版本?您的预期结果是什么。 -
对不起大家,我在测试时粘贴了代码 includig only }。现在我在正则表达式中添加了 { 和 } 。也许我还应该指定:php 7.0
-
我的预期结果是 [1] => Array([type] => alpha[text] => cats{1})
标签: php regex unicode word-boundary named-captures