So I want to remove space between tags. The tags are seperated by comma. But I don't want to remove space between words just right after the commas.
So this:
cats, funny cats, cute cats, funny
To this:
cats,funny cats,cute cats,funny

I want them ready for insertion into database.
This is what I have come up with:

<?php

    $tags = 'cats, funny, hair cut, funny hair cut';
    $result = str_replace(', ', ',', $tags);
    echo $tags . '<br />';
    echo $result;

?>

But there might be a problem when the user enters more than one space after the comma. How can I replace it even if the user enters more than one space after a comma. Do I use regular expression? How can I use it?

Hi, you can explode() by comma and trim(), try:

$tags = 'cats, funny, hair cut, funny hair cut';
$result = array_map('trim', explode(',', $tags));

A simple replace should do it:

// removes duple spaces
$result = str_replace("  ", " ", $tags);
// removes space after comma
$result = str_replace(", ", ",", $result);

but yes, regular expression would be better I guess... something like (,[ \s]+) and replace with ","

sorry but not time to test the regex for u know, i'm in a hurry

Thank you cereal, It worked!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.