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.
Use trim()
:
$SEOname = str_replace(' ','-',trim($name));
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);
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));
精彩评论