PHP正则表达式从字符串的开头和结尾开始逗号和空格

时间:2015-06-28 06:27:26

标签: php regex preg-match-all

我有一些像这样的字符串

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

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

并且需要在字符串的开头和结尾删除空格和/或逗号,只使用 preg_replace()尝试了几个正则表达式,但它们会替换所有出现的内容。

编辑:实际上,删除像!@#$%^&*(之类的所有混乱,无论是在字符串的结尾和字符串的开头,都会很棒,但不会介于其间。




可选择通过单词然后逗号然后空格然后另一个单词(如果有逗号一个)来使字符串看起来正确在单词之间)。

示例"One,Two ,Three , Four""One, Two, Three, Four"

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

1 个答案:

答案 0 :(得分:3)

使用正则表达式\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
)