shane
shane

Reputation: 177

php remove from string

Nice quick one for you guys, hope you can help.

After a dodgy CMS I created a while ago, my database is full of product 'names' that have either 1, 2 or 3 spaces before the actual name. This is causing me havoc now and I'm wondering if there's a function that will let me remove these pesky spaces in PHP instead of having to update the database (hundreds of entries).

To make it clearer here's what I'm trying to achieve.

//swap spaces in name for hyphens
$SEOname = str_replace(' ','-',$name);

//works fine on all entries that don't have preceding spaces, but occasionally leads to this
---concrete-fence-posts

Hope you can help.

Thanks.

Upvotes: 0

Views: 1228

Answers (3)

Felix Kling
Felix Kling

Reputation: 816424

Use trim():

$SEOname = str_replace(' ','-',trim($name));

Upvotes: 1

codaddict
codaddict

Reputation: 455020

You can use the ltrim function to get rid of the leading spaces from a string as:

$str = ltrim($str);

In your case it would be used as:

$SEOname = str_replace(' ','-',ltrim($name));

Upvotes: 0

Vincent Savard
Vincent Savard

Reputation: 35927

The php function trim() (Or TRIM() in SQL)

$str = trim("   HELLO   "); // "HELLO"

or

SELECT TRIM("    HELLO    "); // "HELLO"

If the spaces are not necessary, it would be a good idea to remove them from your database (with a query such as UPDATE table_name SET column_name = TRIM(column_name);

Upvotes: 0

Related Questions