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