Removing generated spaces in php
The problem I'm having is removing spaces. I've tried a few different ways and none of them have removed them. I have a drop down menu that has spaces in it so that all the times line up to be easily understood by a customer. It comes through like $str below. Main problem is that once its sent to the mysql database, it replaces the extra spaces with an A with an accent mark. The other problem is, it just doesn't look right in the end with the extra spaces for th开发者_StackOverflow中文版e customer to review before submitting. I'm not clear on the function of mysql_prep but its there as well with trim before the query is ran on the database.
I tried:
$str = " 9:00 AM to 11:00 AM"
$time = str_replace(' ', '', $str);
echo $time; // OUTPUTS " 9:00AM to 11:00AM" // THOSE SPACES DONT NEED TO BE REMOVED
$str = " 9:00 AM to 11:00 AM"
$time = str_replace(' ', '', $str); //NOTE THE EXTRA SPACE
echo $time; // OUTPUTS " 9:00 AM to 11:00 AM"
$str = " 9:00 AM to 11:00 AM"
$time = str_replace(' ', '', $str); //EVEN TRIED THIS EVEN THOUGH THERES NO WAY
echo $time; // OUTPUTS " 9:00 AM to 11:00 AM"
And
$str = " 9:00 AM to 11:00 AM"
$time = preg_replace('/\s+/', '', $str);
echo $time; // OUTPUTS "???9:00 AM??to??11:00 AM"//SEEMS CLOSEST BUT THE TRIANGLE QUESTION MARKS REPLACE THE SPACES
$str = " 9:00 AM to 11:00 AM"
$time = preg_replace('/\s\s+/', ' ', $str);
echo $time; // OUTPUTS " 9:00 AM to 11:00 AM"
I even tried using explode and trim to do it in a round about way and even trim didn't remove the spaces. Versions I'm using; PHP:5.3.4, MySQL:5.1.53 & Firefox:5.0.1
A non-breaking space is not a normal space.
str_replace("\xa0",'',$string);
Or to get all other whitespace in there:
preg_replace("/[\xa0\s]{2,}/",'',$string);
And be aware of character encoding, you seem to have some issues with that.
Use this :
$string = preg_replace('/\s+/', '', $string);
okay bit more code but works
$str = " 9:00 AM to 11:00 AM";
$find_cln = array (' ','to','AM','PM'); // find
$rep_cln = array ('',' to ',' AM',' PM'); // replace
$str = str_replace($find_cln, $rep_cln, $str);
精彩评论