正则表达式-preg_replace-一个返回空格,另一个不返回任何内容

问题描述 投票:1回答:1

我正在清理UTF-8字符串:大写首字母-删除特殊字符-允许空间-以逗号分隔和允许的数字

我想知道,是否有可能创造出比下面更优雅的东西。第一个preg_replace返回一个空格。 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*
php regex utf-8 preg-replace
1个回答
1
投票

您可以删除第一行preg_replace并使用

$clean = preg_replace('~[^\p{L}\d\s]+|(\s)+~u','$1', $element);

它将找到所有出现的

  • [^\p{L}\d\s]+-Unicode字母,数字或空格以外的1个以上字符
  • |-或
  • [(\s)+-1个或多个空格,最后一个空格捕获到组1中。

替换为$1,即捕获到组1中的最后一个空格(因此,除去了最后一个空格之外的所有空格)。

也要在字符串中允许.,只需将其添加到否定的字符类中:

$clean = preg_replace('~[^\p{L}\d\s.]+|(\s)+~u','$1', $element);
© www.soinside.com 2019 - 2024. All rights reserved.