正则表达式 - preg_replace - 一个返回 space,另一个什么都不返回
Regular Expression - preg_replace - One returning space, the other returning nothing
我正在清理 UTF-8 字符串:首字母大写 - 删除特殊字符 - 允许 Space - 逗号分隔和允许数字
我想知道是否有可能创造出比下面更优雅的东西。
第一个preg_replacereturns一个Space。 other 什么都不替换。
$cleanCats = array_map(function ($element) {
$oneSpace = preg_replace('!\s+!', ' ', $element);
$clean = preg_replace('~[^\pL\d ]+~u','',$oneSpace);
return mb_strtoupper(mb_substr($clean, 0, 1)) . mb_substr($clean, 1);
}, $arrFromHtml);
echo json_encode('*' . strip_tags(implode(',', $cleanCats)) . '*');
$arrFromHtml 看起来像这样:
Array
(
[0] => B:.M¤%&/W
[1] => λgreek
[2] => бжÐrussian
[3] => H<>elloj
[4] => com,m()/a
[5] => Åó*dź
[6] => 1 spc
[7] => 3 spc
[8] => æøå danish
[9] => Euroâ¬
)
这是输出:
*BMW,Λgreek,БжЖrussian,Helloj,Comma,Łódź,1 spc,3 spc,Æøå danish,Euro*
您可以删除第一行 preg_replace
并使用
$clean = preg_replace('~[^\p{L}\d\s]+|(\s)+~u','', $element);
它将找到所有出现的
[^\p{L}\d\s]+
- 除了 Unicode 字母、数字或空格之外的 1+ 个字符
|
- 或
(\s)+
- 1 个或多个空格,最后一个捕获到第 1 组。
替换为 </code>,即捕获到组 1 中的最后一个空格(因此,除最后一个空格外的所有空格都被删除)。</p>
<p>要在字符串中也允许<code>.
,只需将其添加到否定字符class:
$clean = preg_replace('~[^\p{L}\d\s.]+|(\s)+~u','', $element);
我正在清理 UTF-8 字符串:首字母大写 - 删除特殊字符 - 允许 Space - 逗号分隔和允许数字
我想知道是否有可能创造出比下面更优雅的东西。 第一个preg_replacereturns一个Space。 other 什么都不替换。
$cleanCats = array_map(function ($element) {
$oneSpace = preg_replace('!\s+!', ' ', $element);
$clean = preg_replace('~[^\pL\d ]+~u','',$oneSpace);
return mb_strtoupper(mb_substr($clean, 0, 1)) . mb_substr($clean, 1);
}, $arrFromHtml);
echo json_encode('*' . strip_tags(implode(',', $cleanCats)) . '*');
$arrFromHtml 看起来像这样:
Array
(
[0] => B:.M¤%&/W
[1] => λgreek
[2] => бжÐrussian
[3] => H<>elloj
[4] => com,m()/a
[5] => Åó*dź
[6] => 1 spc
[7] => 3 spc
[8] => æøå danish
[9] => Euroâ¬
)
这是输出:
*BMW,Λgreek,БжЖrussian,Helloj,Comma,Łódź,1 spc,3 spc,Æøå danish,Euro*
您可以删除第一行 preg_replace
并使用
$clean = preg_replace('~[^\p{L}\d\s]+|(\s)+~u','', $element);
它将找到所有出现的
[^\p{L}\d\s]+
- 除了 Unicode 字母、数字或空格之外的 1+ 个字符|
- 或(\s)+
- 1 个或多个空格,最后一个捕获到第 1 组。
替换为 </code>,即捕获到组 1 中的最后一个空格(因此,除最后一个空格外的所有空格都被删除)。</p>
<p>要在字符串中也允许<code>.
,只需将其添加到否定字符class:
$clean = preg_replace('~[^\p{L}\d\s.]+|(\s)+~u','', $element);