Featured Posts

How to capitalize, lowercase letters in a string using PHP

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

0

Use ucfirst( ) to capitalize the first character in a string:

<?php
print ucfirst(‘monkey face’);
print ucfirst(’1 monkey face’);
?>

Output:

Monkey face
1 monkey face

Note that the second phrase is not “1 Monkey face.”

Use ucwords( ) to capitalize the first character of each word in a string:

<?php
print ucwords(’1 monkey face’);
print ucwords(“don’t play zone defense against the philadelphia 76-ers”);
?>

Output:

1 Monkey Face
Don’t Play Zone Defense Against The Philadelphia 76-ers

As expected, ucwords( ) doesn’t capitalize the “t” in “don’t.” But it also doesn’t capitalize the “e” in “76-ers.” For ucwords( ), a word is any sequence of nonwhitespace characters that follows one or more whitespace characters. Since both ‘ and – aren’t whitespace characters, ucwords( ) doesn’t consider the “t” in “don’t” or the “e” in “76-ers” to be word-starting characters.
Both ucfirst( ) and ucwords( ) don’t change the case of non-first letters:

<?php
print ucfirst(‘macWorld says I should get an iBook’);
print ucwords(‘eTunaFish.com might buy itunaFish.Com!’);
?>

Output:
MacWorld says I should get an iBook
ETunaFish.com Might Buy ItunaFish.Com!

The functions strtolower( ) and strtoupper( ) work on entire strings, not just individual characters. All alphabetic characters are changed to lowercase by strtolower( ) and strtoupper( ) changes all alphabetic characters to uppercase:

<?php
print strtolower(“I programmed the WOPR and the TRS-80.”);
print strtoupper(‘”since feeling is first” is a poem by e. e. cummings.’);
?>

Output:
i programmed the wopr and the trs-80.
“SINCE FEELING IS FIRST” IS A POEM BY E. E. CUMMINGS.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

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.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to Process a String One Byte at a Time in PHP

Posted by albert | Posted in PHP, Software Programs, Theory Subjects | Posted on 19-11-2009

0

Processing each byte in a string

<?php
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
    if (strstr('aeiouAEIOU',$string[$i])) {
        $vowels++;
    }
}
?>

Processing a string a character at a time is an easy way to calculate the “Look and Say” sequence

<?php
function lookandsay($s) {
// initialize the return value to the empty string

    $r = '';
    // $m holds the character we're counting, initialize to the first
    // character in the string
    $m = $s[0];
    // $n is the number of $m's we've seen, initialize to 1
    $n = 1;
    for ($i = 1, $j = strlen($s); $i < $j; $i++) {
        // if this character is the same as the last one
        if ($s[$i] == $m) {
            // increment the count of this character
            $n++;
        } else {
            // otherwise, add the count and character to the return value
            $r .= $n.$m;
            // set the character we're looking for to the current one
            $m = $s[$i];
            // and reset the count to 1
            $n = 1;
        }
    }
    // return the built up string as well as the last count and character
    return $r.$n.$m;
}
for ($i = 0, $s = 1; $i < 10; $i++) {
    $s = lookandsay($s);
    print "$s <br/>\n";
}

Output

1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211

It’s called the “Look and Say” sequence because each element is what you get by looking at the previous element and saying what’s in it. For example, looking at the first element, 1, you say “one one.” So the second element is “11.” That’s two ones, so the third element is “21.” Similarly, that’s one two and one one, so the fourth element is “1211,” and so on.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Accessing Substrings in PHP

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

0

If we want to know if a string contains a particular substring. For example, you want to find out if an email address contains a @

Use strpos( )

Finding a substring with strpos( )

<?php
if (strpos($_POST['email'], '@') === false) {
   print 'There was no @ in the e-mail address!';
 }
?>
The return value from strpos( ) is the first position in the string
(the "haystack") at which the substring (the "needle") was found.
If the needle wasn't found at all in the haystack, strpos( ) returns
false. If the needle is at the beginning of the haystack, strpos( )
returns 0, since position 0 represents the beginning of the string.
To differentiate between return values of 0 and false, you must
use the identity operator (===) or the notidentity operator (!==)
instead of regular equals (==) or not-equals (!=).
VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to insert Double-quoted strings in PHP

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

0

Sample Program

print "I've gone to the store.";
print "The sauce cost \$10.25.";
$cost = '$10.25';
print "The sauce cost $cost.";
print "The sauce cost \$\061\060.\x32\x35.";
Output
I've gone to the store.
The sauce cost $10.25.
The sauce cost $10.25.
The sauce cost $10.25.

The last line of prints the price of sauce  correctly because the character 1 is ASCII code 49 decimal and 061  octal. Character 0 is ASCII 48 decimal and 060 octal; 2 is  ASCII 50 decimal and 32 hex; and 5 is ASCII 53 decimal and 35 hex.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to insert Single-quoted strings in PHP

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

0

Single-quoted strings

print 'I have gone to the store.';
print 'I\'ve gone to the store.';
print 'Would you pay \$1.75 for 8 ounces of tap water?';
print 'In double-quoted strings, newline is represented by \n';

Output

I have gone to the store.
I've gone to the store.
Would you pay $1.75 for 8 ounces of tap water?
In double-quoted strings, newline is represented by \n

Because PHP doesn’t check for variable interpolation or almost any escape sequences in single-quoted strings, defining strings this way is straightforward and fast.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Dynamic Function Calls in PHP

Posted by admin | Posted in PHP, Theory Subjects | Posted on 18-11-2009

0

1: <!DOCTYPE html PUBLIC
2:   “-//W3C//DTD XHTML 1.0 Strict//EN”
3:   “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
4: <html>
5: <head>
6: <title>Calling a Function Dynamically</title>
7: </head>
8: <body>
9: <div>
10: <?php
11: function sayHello() {
12:   print “hello<br />”;
13: }
14: $function_holder = “sayHello”;
15: $function_holder();
16: ?>
17: </div>
18: </body>
19: </html>

A string identical to the name of the sayHello() function is assigned to the $function_holder variable on line 14. After this is done, we can use this variable in conjunction with parentheses to call the sayHello() function. We do this on line 15.

Why would we want to do this? In the example, we simply made more work for ourselves by assigning the string "sayHello" to $function_holder. Dynamic function calls are useful when you want to alter program flow according to changing circumstances. We might want our script to behave differently according to a parameter set in a URL’s query string, for example. We could extract the value of this parameter and use it to call one of a number of functions.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Difference between Multitasking and Multithreading

Posted by albert | Posted in PHP, Theory Subjects | Posted on 16-11-2009

0

Multitasking is the ability of an operating system to run multiple programs concurrently. Basically, the operating system uses a hardware clock to allocate “time slices” for each currently running process. If the time slices are small enough—and the machine is not overloaded with too many programs trying to do something—it appears to a user as if all the programs are running simultaneously.

Multitasking is nothing new. On large mainframe computers, multitasking is a given. These mainframes often have hundreds of terminals attached to them, and each terminal user should get the impression that he or she has exclusive access to the whole machine. In addition, mainframe operating systems often allow users to “submit jobs to the background,” where they are then carried out by the machine while the user can work on something else.

Multitasking on personal computers has taken much longer to become a reality. But we now often seem to take PC multitasking for granted. As I’ll discuss shortly, to some extent the earlier 16-bit versions of Microsoft Windows supported multitasking but in a somewhat limited capability. The 32-bit versions of Windows all support both true multitasking and—as an extra bonus—multithreading.

Multithreading is the ability for a program to multitask within itself. The program can split itself into separate “threads” of execution that also seem to run concurrently. This concept might at first seem barely useful, but it turns out that programs can use multithreading to perform lengthy jobs in the background without requiring the user to take an extended break away from their machines. Of course, sometimes this may not be desired: an excuse to take a journey to the watercooler or refrigerator is often welcome! But the user should always be able to do something on the machine, even when it’s busy doing something else.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

I’m still confused. I just can’t understand all this null pointer stuff.

Posted by albert | Posted in PHP, Request | Posted on 16-11-2009

0

A simple rule is, “Always use `0′ or `NULL’ for null pointers, and always cast them when they are used as arguments in function calls.”

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Why is there so much confusion surrounding null pointers? Why do these questions come up so often?

Posted by albert | Posted in PHP, Request | Posted on 16-11-2009

0

The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions.  The use of a  preprocessor macro (NULL) suggests that the value might change later, or on some weird machine.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)