HMV.co.in

September 28, 2008

Remove blank spaces and new lines from string

Filed under: php — Tags: , , , , , — Harsha M V @ 2:55 am

you can use the preg_replace function to compress a given string and remove spaces and blank lines from the string.

The use of the function is as given below:

preg_replace(”/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/”, “\n”, $string);

where “$string” is the string you want to remove the spaces and blank lines from.

if in case the above code doesn’t work properly you can use the below given user-defined function :

The Function:

function my_preg_rep($content_area){
$content_area=preg_replace(”/[\r\n]*/”, “”, $content_area);
$content_area=preg_replace(”/[\r\n]+/”, “”, $content_area);
return $content_area;
}

Code :

echo my_preg_rep(addslashes($content_area));

September 23, 2008

Remove whitespace from a text string using the PHP trim function

Filed under: php — Tags: , , , — Harsha M V @ 10:56 pm

Description

If you use a form on your site then you’ll know that user input can often have white space before or after the text as the person filling in the form field sometimes accidentally adds spaces. This handy function will remove the whitespace from the beginning or end of the string.

The code


<?php

// The original text string with whitespace at the end

$textString "This is some text with a space after it ";

// Remove the whitespace

$trimmedTextString trim($textString);

// Display the new text string

echo $trimmedTextString;

?>

Blog at WordPress.com.