views:

22

answers:

4

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.

A: 

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);

Vincent Savard
Fantastic. Thanks very much.
shane
A: 

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));
codaddict
+1  A: 

Use trim():

$SEOname = str_replace(' ','-',trim($name));
Felix Kling
A: 

Trim leading spaces first with ltrim(), then replace.

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

If you want to eliminate whitespace from both ends, use trim().

BoltClock