0

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.

3 Answers 3

1

Use trim():

$SEOname = str_replace(' ','-',trim($name));
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.