Variable contain valid number using PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 08-12-2009

0

How to check whether variable contains valid number using PHP

You want to ensure that a variable contains a number, even if it’s typed as a string. Alternatively, you want to check if a variable is not only a number, but is also specifically typed as a one.

Use is_numeric( ) to discover whether a variable contains a number:

<?php
if (is_numeric(5))          { /* true  */ }
if (is_numeric(‘5′))        { /* true  */ }
if (is_numeric(“05″))       { /* true  */ }
if (is_numeric(‘five’))     { /* false */ }

if (is_numeric(0xDECAFBAD)) { /* true  */ }
if (is_numeric(“10e200″))   { /* true  */ }
?>

Numbers come in all shapes and sizes. You cannot assume that something is a number simply because it only contains the characters 0 through 9. What about decimal points, or negative signs? You can’t simply add them into the mix because the negative must come at the front, and you can only have one decimal point. And then there’s hexadecimal numbers and scientific notation.

Instead of rolling your own function, use is_numeric( ) to check whether a variable holds something that’s either an actual number (as in it’s typed as an integer or floating point), or it’s a string containing characters that can be translated into a number.

There’s an actual difference here. Technically, the integer 5 and the string 5 aren’t the same in PHP. However, most of the time you won’t actually be concerned about the distinction, which is why the behavior of is_numeric( ) is useful.

Helpfully, is_numeric( ) properly parses decimal numbers, such as 5.1; however, numbers with thousands separators, such as 5,100, cause is_numeric( ) to return false.

To strip the thousands separators from your number before calling is_numeric( ), use str_replace( ):

<?php
is_numeric(str_replace($number, ‘,’, ”));
?>

To check if your number is a specific type, there are a variety of related functions with self-explanatory names: is_float( ) (or is_double( ) or is_real( ); they’re all the same) and is_int( ) (or is_integer( ) or is_long( )).

To validate input data, use the techniques from Recipe 9.3 instead of is_numeric( ). That recipe describes how to check for positive or negative integers, decimal numbers, and a handful of other formats.

How to Switching tabs and spaces in PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 20-11-2009

0

Use str_replace( ) to switch spaces to tabs or tabs to spaces
Example

<?php
$r = mysql_query(“SELECT message FROM messages WHERE id = 1″) or die();
$ob = mysql_fetch_object($r);
$tabbed = str_replace(‘ ‘,”\t”,$ob->message);
$spaced = str_replace(“\t”,’ ‘,$ob->message);
print “With Tabs: <pre>$tabbed</pre>”;
print “With Spaces: <pre>$spaced</pre>”;
?>

Using str_replace( ) for conversion, however, doesn’t respect tab stops. If
you want tab stops every eight characters, a line beginning with a five-letter
word and a tab should have that tab replaced with three spaces, not one.
Use the pc_tab_expand( ) function
pc_tab_expand( )

<?php
function pc_tab_expand($text) {
while (strstr($text,”\t”)) {
$text = preg_replace_callback(‘/^([^\t\n]*)(\t+)/m’,'pc_tab_expand_helper’, $text);
}
return $text;
}
function pc_tab_expand_helper($matches) {
$tab_stop = 8;
return $matches[1] .
str_repeat(‘ ‘,strlen($matches[2]) *
$tab_stop – (strlen($matches[1]) % $tab_stop));
}
$spaced = pc_tab_expand($ob->message);
?>

You can use the pc_tab_unexpand( ) function to turn spaces back to tabs
pc_tab_unexpand( )

<?php
function pc_tab_unexpand($text) {
$tab_stop = 8;
$lines = explode(“\n”,$text);
foreach ($lines as $i => $line) {
// Expand any tabs to spaces
$line = pc_tab_expand($line);
$chunks = str_split($line, $tab_stop);
$chunkCount = count($chunks);
// Scan all but the last chunk
for ($j = 0; $j < $chunkCount – 1; $j++) {
$chunks[$j] = preg_replace(‘/ {2,}$/’,”\t”,$chunks[$j]);
}
// If the last chunk is a tab-stop’s worth of spaces
// convert it to a tab; Otherwise, leave it alone
if ($chunks[$chunkCount-1] == str_repeat(‘ ‘, $tab_stop)) {
$chunks[$chunkCount-1] = “\t”;
}
// Recombine the chunks
$lines[$i] = implode(”,$chunks);
}
// Recombine the lines
return implode(“\n”,$lines);
}
$tabbed = pc_tab_unexpand($ob->message);
?>

Both functions take a string as an argument and return the string appropriately modified.
Each function assumes tab stops are every eight spaces, but that can be modified by changing the setting of the $tab_stop variable.
The regular expression in pc_tab_expand( ) matches both a group of tabs and all the text in a line before that group of tabs. It needs to match the text before the tabs because the length of that text affects how many spaces the tabs should be replaced with so that subsequent text is aligned with the next tab stop. The function doesn’t just replace each tab with eight spaces; it adjusts text after tabs to line up with tab stops.
Similarly, pc_tab_unexpand( ) doesn’t just look for eight consecutive spaces and then replace them with one tab character. It divides up each line into eight-character chunks and then substitutes ending whitespace in those chunks (at least two spaces) with tabs. This not only preserves text alignment with tab stops; it also saves space in the string.