0

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?

3
Contributors
3
Replies
15
Views
1 Year
Discussion Span
Last Post by FarrisFahad
1

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

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

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

Edited by AleMonteiro

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.