Skip to content
Advertisement

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

I have some strings like this

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

EDIT 2: Some strings have two words between coma like ", Two ,Three, Twenty Five, Six".

and need to remove space and or comma at the beginning and end of the string only tried few regex with preg_replace(), but they replace all occurrences.

EDIT: Actually would be great to remove all clutter like !@#$%^&*( etc whatever is at the end and beginning of string, but not in between.




Optionally need to make strings look proper by placing word then comma then space then another word (if there’s comma one in between words).

Example "One,Two ,Three , Four" into "One, Two, Three, Four".

P.S. Please provide answer as two separate regex as its easier to understand.

Advertisement

Answer

Use the regex bw+b to extract words and then reformat like this:

<?php

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

?>

Output:

Array
(
    [0] => One
    [1] => One, Two
    [2] => One, Two
    [3] => One, Two
    [4] => Two, Three
    [5] => Two, Three, Twenty Five, Six
)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement