PHP 正则表达式从字符串的开头和结尾去除逗号和 space

PHP regex strip comma and space from beginning and end of string

我有一些像这样的字符串

", One "
", One , Two"
"One, Two "
" One,Two, "
" ,Two ,Three "

编辑 2: 一些字符串在逗号之间有两个单词,如 ", Two ,Three, Twenty Five, Six"

并且需要删除字符串开头和结尾的 space 和/或逗号 只尝试了一些带有 preg_replace 的正则表达式(),但它们会替换所有出现的地方。

编辑: 实际上,删除所有杂乱如 !@#$%^&*( 等字符串结尾和开头的任何内容都很好,但不是介于两者之间。




可选地需要通过放置 word 然后 comma 然后 space 然后 另一个单词(如果单词之间有逗号)。

例如 "One,Two ,Three , Four" 变成 "One, Two, Three, Four".

P.S。请将答案作为两个单独的正则表达式提供,因为它更容易理解。

使用正则表达式 \b\w+\b 提取单词,然后像这样重新格式化:

<?php

$strings = [", One ",
    ", One , Two",
    "One, Two ",
    " One,Two, ",
    " ,Two ,Three ",
    ", Two ,Three, Twenty Five, Six"];
foreach($strings as &$str)
{
    preg_match_all('/\b[\w\s]+\b/',$str,$matches);
    $neat = '';
    foreach($matches[0] as $word)
    {
        $neat .= $word.', ';
    }
    $neat = rtrim($neat,', ');
    $str = $neat;
}
print_r($strings);

?>

输出:

Array
(
    [0] => One
    [1] => One, Two
    [2] => One, Two
    [3] => One, Two
    [4] => Two, Three
    [5] => Two, Three, Twenty Five, Six
)

由于您想将输入字符串变为一致的逗号+space 分隔字符串,因此没有理由形成临时数组——特别是如果您对正则表达式技术持开放态度。

  1. trim输入字符串前后的所有space和逗号,然后
  2. 用您的标准化逗号+space 胶水替换一个或多个逗号或 space 个字符。

代码:(Demo)

$tests = [
    ", One ,,  ,,",
    ", Two , Three",
    "Four, Five ",
    " Six,Seven, ",
    " ,Eight ,Nine , , , , Ten ,",
];

foreach ($tests as $test) {
    var_export(
        preg_replace('/[, ]+/', ', ', trim($test, ', '))
    );
    echo "\n";
}

输出:

'One'
'Two, Three'
'Four, Five'
'Six, Seven'
'Eight, Nine, Ten'

如果您要求 在您的输入字符串中至少使用一个逗号作为分隔序列,则此调整后的正则表达式可以:/[, ]*,[, ]*/。演示:https://3v4l.org/HeCFp 这将在一个值内保留 spaces。

",,Eleventy Twelve , , Thrirteen " -> "Eleventy Twelve, Thrirteen"


如果要删除输入字符串开头和结尾的“垃圾字符”,只需将 !@#$%^&*( 个字符添加到 trim() 的“字符掩码”参数中 --> , !@#$%^&*(.