krystian
krystian

Reputation: 15

remove spaces from string PHP and insert to database

I'm trying to remove spaces from string but only from beggining and end of the string. Everythink work fine but after insert string to database there is no spaces but in the same place is "�".

Here is my code:

$synonimy = $_POST['fsynoms'];
$synonimyPodzielone = explode( ',', $synonimy );
for($k=0; $k < count($synonimyPodzielone); $k++)
{
    for($m=0; $m<strlen($synonimyPodzielone[$k]);$m++)
    {

        if($synonimyPodzielone[$k][$m]==" ")
        {
            $synonimyPodzielone[$k][$m]="";
        }
        else
        {
            break;
        }
    }
}

I have also tryied with str_replace trim and same problem.

Any idea how to do that?

Upvotes: 1

Views: 4530

Answers (5)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

using strtr is also possible (and fast):

$synonimy = trim($_POST['fsynoms']);
$synonimy = strtr($synonimy, array(' ,' => ',', ', '=>','));

Note: if your string contains duplicate spaces you want to remove, in this case you can use this:

$synonimy = preg_replace('~\s*(,)\s*|\A\s+|\s+\z~u', '$1', $_POST['fsynoms']);

that deals with unicode strings.

Upvotes: 0

nikc.org
nikc.org

Reputation: 16952

What you're looking for is trim. With the help of array_map you can even skip the for loop.

$input = " foo , bar , baz , qux ";
$words = explode(",", $input);
$wordsTrimmed = array_map("trim", $words);
$csvString = implode(",", $wordsTrimmed);

echo $csvString; // foo,bar,baz,qux

You can of course make it neater:

function trimWords($string, $glue = ",") {
    return implode($glue, array_map("trim", explode($glue, $string)));
}

$input = " foo , bar , baz , qux ";
$csvString = trimWords($input);

echo $csvString; // foo,bar,baz,qux

Upvotes: 1

Christian Hagdorn
Christian Hagdorn

Reputation: 463

Or even simpler.

$synonimy = trim($_POST['fsynoms']);
insert_into_database($synonimy);

Upvotes: 0

Martin
Martin

Reputation: 22760

PHP Trim: http://php.net/manual/en/function.trim.php should make life much easier.

for($m=0; $m<strlen($synonimyPodzielone[$k]);$m++)
{
    $synonimyPodzielone[$k][$m] = trim($synonimyPodzielone[$k][$m]);    
}

Upvotes: 1

Dai
Dai

Reputation: 155035

The trim($str) function ( http://php.net/manual/en/function.trim.php ) is hard to use incorrectly, were you just not storing the return value? (the trim function in PHP does not modify the argument, it instead returns a new string with whitespace removed).

$synonimy = $_POST['fsynoms'];
$synonimy = trim( $synonimy );

insert_into_database( $synonimy );

Upvotes: 1

Related Questions