Tuesday, February 3, 2009

Trimming each line: trim() function

Just a few days ago, i ran into this problem of needing to trim off spaces in front and behind of each line of a string with multiline. so i came up with this simple function to do the job.

function trimlines($s,$t){
$e = explode("\n",$s);
foreach($e as $i => $a){$e[i] = trim($a,$t)}
return implode("\n",$e);
}


Optimized-for-speed version:
function trimlines($s,$t){
$e = explode("\n",$s);$z = count($e);
while($z-->0){$e[z] = trim($e[z],$t)}
return implode("\n",$e);
}


simple, ain't it?

No comments: