Jump to content

remove white space from variable


chanchelkumar

Recommended Posts

Hi

 

actually i am working with a script which pull data from database and display in excelsheet (CSV) , in which i want to receive the data with out white space or "blank" ..

 

i tried with trim,preg_replace and also arrays for this...

 

Am still in the circle.....

please help me.....

 

Thanks in advance.....

Link to comment
https://forums.phpfreaks.com/topic/80603-remove-white-space-from-variable/
Share on other sites

If you wish to remove ALL white spaces, you can use str_replace:

 

<?php
$sql = "SELECT `dataField` FROM `dataTable`";
if ( !$result = mysql_query($sql) ) {
   die('MySQL Error: ' . mysql_error());
}
while ( list($data) = mysql_fetch_assoc($result) ) {
   $data = str_replace(' ', '', $data);
   // do whatever else
}
// code continues

 

PhREEEk

from http://www.php.net/preg_replace

 

Example#5 Strip whitespace

 

This example strips excess whitespace from a string.

<?php

$str = 'foo  o';

$str = preg_replace('/\s\s+/', ' ', $str);

// This will be 'foo o' now

echo $str;

?>

 

not sure if i understood you rignt, you want to insert the data you take from a database into a csv.

the function works, tested it. now you can do a str_replace(" ","<your delimiter>","$string) and write it into the csv... if i understood wrong, please correct me

But this is working only for a single space....

 

my contents having lot of whitespace....

 

For example:

 

">new firstline                                                                                             

 

 

 

 

 

Fifthline space contiues.....                                                                           

 

 

 

 

 

 

 

End of opace";

 

how to remove this space..

  • 2 weeks later...
  • 2 months later...

In case the problem has not been solved yet, or maybe someone new is facing a similar problem... Here is the code to remove excessive whitespace from a string.

 

ereg_replace('[[:space:]]+', ' ', trim($str));

 

Details see code example at: http://www.thewebscripter.com/tutorial/code_examples/remove_whitespace.php

 

Hope this helps.

 

Alex

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.