Removing spaces from a string with ColdFusion or php

August 12th, 2008

This is one of those little problems that pop up frequently and to show how it’s done in CFML as well as our other house language PHP, we’ve put these examples up for you. This method is using a regular expression.

To remove ALL the spaces from a string:

1
2
3
4
5
6
<!--- set up a test variable --->
<cfset mySpaceFilledString = " east coast interactive love coldfusion " />
<!--- remove ALL spaces from the string --->
<cfset mySpaceFreeVariable = ReReplace(mySpaceFilledString, "[[:space:]]","","ALL")>
<!--- check it works --->
<cfdump var = #mySpaceFreeVariable#>

The above returns “eastcoastinteractivelovecoldfusion” – all spaces have been removed

And the PHP version

1
2
3
4
5
6
7
8
<?php
// set up a test variable
$mySpaceFilledString = " east coast interactive love php ";
// remove all spaces from the string
$mySpaceFreeVariable = str_replace(" ", "", $mySpaceFilledString);
// check it works
echo $mySpaceFreeVariable;
?>

The above returns “eastcoastinteractivelovephp” – again, all spaces have been removed

To simply remove the spaces at the start and end of a string:

1
2
3
4
5
6
<!--- set up a test variable --->
<cfset mySpaceFilledString = " east coast interactive love coldfusion " />
<!--- remove spaces from start and end of the string --->
<cfset mySpaceFreeVariable = Trim(mySpaceFilledString)>
<!--- check it works --->
<cfdump var = #mySpaceFreeVariable#>

The above returns “east coast interactive love coldfusion” – spaces at the start and end have been removed only

And the PHP version

1
2
3
4
5
6
7
8
<?php
// set up a test variable
$mySpaceFilledString = " east coast interactive love php ";
// remove spaces from start and end of the string
$myTrimmedVariable = trim($mySpaceFilledString);
//check it works
echo $myTrimmedVariable;
?>

The above returns “east coast interactive love php” – again, all spaces have been removed from the start and end only.

Entry Filed under: coldfusion, php

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed

Calendar

October 2017
M T W T F S S
« Feb    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Categories

Most Recent Posts

Feeds