Remove Spaces from a String using PHPt.
This is quite a funny one for me. As you may or may not know I’m not a guru PHP developer but I do know a little from my time as a web designer/developer. Today I had to do something as simple as removing spaces from a variable string using PHP.
After a quick think about how I was going to do this I put together some code that would remove the spaces.
$mobile = ” 0400 000 000″;
//echo $mobile;
$mobile = trim($mobile);
$numcount = strlen($mobile);
//echo $numcount;
$ptr=0;
while ($i <= $numcount) { //Loop until testing of all numerals in ph no
if ($mobile{$ptr} != ” “) {
$ptr++;
}else{
$mobiletemp = substr($mobile, 0, $ptr);
echo “mobiletemp:”.$mobiletemp.”\n”;
$mobile = $mobiletemp.substr($mobile,($ptr+1),$numcount);
echo “mobile :”.$mobile;
$ptr++;
};
$i++;
}
So here I was really proud of myself for cooking up such an elaborate chunk of code that would do what I needed. During the process of writing the code I posted a question on a developer forum asking for a quick way of removing the spaces. By the time I finished my piece of code I had a response from the developer forum.
And here was their solution
$mobile = str_replace ( ‘ ‘, ”, $mobile );
That’s right. Just one line of code to do the same thing as my 18 lines of code. Same solution different method.
Hopefully someone who like me needs to know how to do this in a hurry and will find this post.
Recent Comments