Featured Posts

How to Wrap the Text in PHP

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

0

You need to wrap lines in a string. For example, you want to display text in <pre>/</pre> tags but have it stay within a regularly sized browser window.
Use wordwrap( ) :

<?php
$s = “Four score and seven years ago our fathers brought forth

on this continent a new nation, conceived in liberty and

dedicated to the proposition that all men are created equal.”;

print “<pre>\n”.wordwrap($s).”\n</pre>”;
?>

Output

<pre>
Four score and seven years ago our fathers brought forth on this continent
a new nation, conceived in liberty and dedicated to the proposition that
all men are created equal.
</pre>

By default, wordwrap( ) wraps text at 75 characters per line. An optional second argument specifies different line length:

<?php
print wordwrap($s,50);
?>

Output

Four score and seven years ago our fathers brought
forth on this continent a new nation, conceived in
liberty and dedicated to the proposition that all
men are created equal.

Other characters besides \n can be used for line breaks. For double spacing, use “\n\n”:

<?php
print wordwrap($s,50,”\n\n”);
?>

Output

Four score and seven years ago our fathers brought

forth on this continent a new nation, conceived in

liberty and dedicated to the proposition that all

men are created equal.

There is an optional fourth argument to wordwrap( ) that controls the treatment of words that are longer than the specified line length. If this argument is 1, these words are wrapped. Otherwise, they span past the specified line length:

<?php
print wordwrap(‘jabberwocky’,5);
print wordwrap(‘jabberwocky’,5,”\n”,1);
?>
Output
jabberwocky
jabbe
rwock
y

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 break a string into pieces in PHP

Posted by admin | Posted in PHP, Software Programs | Posted on 24-11-2009

0

You need to break a string into pieces. For example, you want to access each line that a user enters in a <textarea> form field.
Use explode( ) if what separates the pieces is a constant string:

<?php
$words = explode(‘ ‘,’My sentence is not very complicated’);
?>

Use split( ) or preg_split( ) if you need a POSIX or Perl-compatible regular expression to describe the separator:

<?php
$words = split(‘ +’,'This sentence  has  some extra whitespace  in it.’);
$words = preg_split(‘/\d\. /’,'my day: 1. get up 2. get dressed 3. eat toast’);
$lines = preg_split(‘/[\n\r]+/’,$_REQUEST['textarea']);
?>

Use spliti( ) or the /i flag to preg_split( ) for case-insensitive separator matching:

<?php
$words = spliti(‘ x ‘,’31 inches x 22 inches X 9 inches’);
$words = preg_split(‘/ x /i’,’31 inches x 22 inches X 9 inches’);
?>

The simplest solution of the bunch is explode( ). Pass it your separator string, the string to be separated, and an optional limit on how many elements should be returned:

<?php
$dwarves = ‘dopey,sleepy,happy,grumpy,sneezy,bashful,doc’;
$dwarf_array = explode(‘,’,$dwarves);
?>

This makes $dwarf_array a seven-element array, so print_r($dwarf_array) prints:
Array
(
[0] => dopey
[1] => sleepy
[2] => happy
[3] => grumpy
[4] => sneezy
[5] => bashful
[6] => doc
)

If the specified limit is less than the number of possible chunks, the last chunk contains the remainder:

<?php
$dwarf_array = explode(‘,’,$dwarves,5);
print_r($dwarf_array);
?>

This prints:
Array
(
[0] => dopey
[1] => sleepy
[2] => happy
[3] => grumpy
[4] => sneezy,bashful,doc
)

The separator is treated literally by explode( ). If you specify a comma and a space as a separator, it breaks the string only on a comma followed by a space, not on a comma or a space.
With split( ), you have more flexibility. Instead of a string literal as a separator, it uses a POSIX regular expression:

<?php
$more_dwarves = ‘cheeky,fatso, wonder boy, chunky,growly, groggy, winky’;
$more_dwarf_array = split(‘, ?’,$more_dwarves);
?>

This regular expression splits on a comma followed by an optional space, which treats all the new dwarves properly. A dwarf with a space in his name isn’t broken up, but everyone is broken apart whether they are separated by “,” or “, “. print_r($more_dwarf_array) prints:
Array
(
[0] => cheeky
[1] => fatso
[2] => wonder boy
[3] => chunky
[4] => growly
[5] => groggy
[6] => winky
)

Similar to split( ) is preg_split( ), which uses a Perl-compatible regular expression engine instead of a POSIX regular expression engine. With preg_split( ), you can take advantage of various Perl-ish regular expression extensions, as well as tricks such as including the separator text in the returned array of strings:

<?php
$math = “3 + 2 / 7 – 9″;
$stack = preg_split(‘/ *([+\-\/*]) */’,$math,-1,PREG_SPLIT_DELIM_CAPTURE);
print_r($stack);
?>

This prints:
Array
(
[0] => 3
[1] => +
[2] => 2
[3] => /
[4] => 7
[5] => -
[6] => 9
)

The separator regular expression looks for the four mathematical operators (+, -, /, *), surrounded by optional leading or trailing spaces. The PREG_SPLIT_DELIM_CAPTURE flag tells preg_split( ) to include the matches as part of the separator regular expression in parentheses in the returned array of strings. Only the mathematical operator character class is in parentheses, so the returned array doesn’t have any spaces in it.

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 Create Comma Separated Data in PHP

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

0

Use the fputcsv( ) function to generate a CSV-formatted line from an array of data.  Writes the data in $sales into a file

Sample Program

<?php
$sales = array( array(‘Northeast’,’2005-01-01′,’2005-02-01′,12.54),
array(‘Northwest’,’2005-01-01′,’2005-02-01′,546.33),
array(‘Southeast’,’2005-01-01′,’2005-02-01′,93.26),
array(‘Southwest’,’2005-01-01′,’2005-02-01′,945.21),
array(‘All Regions’,'–’,'–’,1597.34) );
ob_start();
$fh = fopen(‘php://output’,'w’) or die(“Can’t open php://output”);
foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) {
die(“Can’t write CSV line”);
}
}
fclose($fh) or die(“Can’t close php://output”);
$output = ob_get_contents();
ob_end_clean();
?>

<?php
$sales = array( array(‘Northeast’,’2005-01-01′,’2005-02-01′,12.54),
array(‘Northwest’,’2005-01-01′,’2005-02-01′,546.33),
array(‘Southeast’,’2005-01-01′,’2005-02-01′,93.26),
array(‘Southwest’,’2005-01-01′,’2005-02-01′,945.21),
array(‘All Regions’,'–’,'–’,1597.34) );

$fh = fopen(‘sales.csv’,'w’) or die(“Can’t open sales.csv”);
foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) {
die(“Can’t write CSV line”);
}
}
fclose($fh) or die(“Can’t close sales.csv”);
?>

Putting comma-separated data into a string

Printing comma-separated data

<?php $sales = array( array('Northeast','2005-01-01','2005-02-01',12.54),
                array('Northwest','2005-01-01','2005-02-01',546.33),
                array('Southeast','2005-01-01','2005-02-01',93.26),
                array('Southwest','2005-01-01','2005-02-01',945.21),
                array('All Regions','--','--',1597.34) );
$fh = fopen('php://output','w');
foreach ($sales as $sales_line) {
    if (fputcsv($fh, $sales_line) === false) {
        die("Can't write CSV line");
    }
}
fclose($fh);
?>
VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: +1 (from 1 vote)

How to Trim Blanks from a String using PHP

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

0

Use ltrim( ), rtrim( ), or trim( ), ltrim( ) removes whitespace from the beginning of a string, rtrim( ) from the end of a string, and trim( ) from both the beginning and end of a string:

<?php
$zipcode = trim($_REQUEST['zipcode']);
$no_linefeed = rtrim($_REQUEST['text']);
$name = ltrim($_REQUEST['name']);
?>
For these functions, whitespace is defined as the following
characters:newline, carriage return, space, horizontal and
vertical tab, and null .

Trimming whitespace off of strings saves storage space and canmake for more
precise display of formatted data or text within<pre> tags, for example. If
you are doing comparisons with userinput, you should trim the data first, so
that someone who mistakenly enters”98052″ as their zip code isn’t forced to
fix an error that really isn’t one. Trimming before exact text comparisons
also ensures that, for example, “salami\n” equals “salami.” It’s also a good
idea to normalize string data bytrimming it before storing it in a database.

The trim( ) functions can also remove user-specifiedcharacters from strings.
Pass the characters you want to remove as a secondargument. You can indicate
a range of characters with two dots between the firstand last characters in
the range:

<?php
// Remove numerals and space from the beginning of the line
print ltrim('10 PRINT A$',' 0..9');
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');
?>

This prints:

PRINT A$
SELECT * FROM turtles

PHP also provides chop( ) asan alias for rtrim( ). However, you’re best off
using rtrim( ) instead because PHP’s chop( ) behaves differently than Perl’s
chop( ) (which is deprecated in favor of chomp( ) , anyway), and using it can
confuse others when they read your code.

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

Interpolating Functions and Expressions Within Strings Using PHP

Posted by Dora_david | Posted in HTML, Software Programs, Theory Subjects | Posted on 23-11-2009

0

You can put variables, object properties, and array elements (if the subscript is unquoted) directly in double-quoted strings:

<?php
print "I have $children children.";
print "You owe $amounts[payment] immediately.";
print "My circle's diameter is $circle->diameter inches.";
?>

Interpolation with double-quoted strings places some limitations on the syntax of what can be interpolated. In the previous example, $amounts['payment'] had to be written as $amounts[payment] so it would be interpolated properly. Use curly braces around more complicated expressions to interpolate them into a string. For example:

<?php
print "I have less than {$children} children.";
print "You owe {$amounts['payment']} immediately.";
print "My circle's diameter is {$circle->getDiameter()} inches.";
?>

Direct interpolation or using string concatenation also works with heredocs. Interpolating with string concatenation in heredocs can look a little strange because the closing heredoc delimiter and the string concatenation operator have to be on separate lines:

<?php
print <<< END
Right now, the time is
END
. strftime('%c') . <<< END
 but tomorrow it will be
END
. strftime('%c',time() + 86400);
?>

Also, if you’re interpolating with heredocs, make sure to include appropriate spacing for the whole string to appear properly. In the previous example, Right now the time has to include a trailing space, and but tomorrow it will be has to include leading and trailing spaces.

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 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)