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.

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.

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.

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.

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 (!=).

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.

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.

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.

Tags and Elements of HTML

Posted by admin | Posted in Theory Subjects, XML | Posted on 17-11-2009

0

If you look at the first and last lines of the code for the last example, you will see pairs of angle brackets containing the letters <html>. The two brackets and all of the characters between them are known as a tag, and there are lots of tags in the example. All of the tags in this example come in pairs; there are
opening tags and closing tags. The closing tag is always slightly different than the opening tag in that it has a forward slash character before the characters </html>.

html

html

The special meaning these tags give is a description of the structure of the document. The opening tag says “This is the beginning of a heading” and the closing tag says “This is the end of a heading.”Without the markup, the words in the middle would just be another bit of text; it would not be clear that they formed the heading.
Now look at the paragraph of text about the company; it is held between an opening <p> tag and a closing </p> tag. And, you guessed it, the p stands for paragraph.

As you can see, the markup in this example actually describes what you will find between the tags, and the added meaning the tags give is describing the structure of the document. For example, between the opening <p> and closing </p> tags are paragraphs and between the <h1> and </h1> tags is a heading. Indeed, the whole HTML document is contained between opening <html> and closing </html> tags.
If you were wondering why there is a number 1 after the h , it is because in HTML and XHTML there are six levels of headings. A level 1 heading is sometimes used as the main heading for a document (such as a chapter title), which can then contain subheadings, with level 6 being the smallest. This allows you to structure your document appropriately with subheadings under the main heading.

Sample HTML program discussion

Posted by admin | Posted in HTML, Software Programs, Theory Subjects | Posted on 17-11-2009

0

HTML, or Hypertext Markup Language, is the most widely used language onWeb. As its name suggests, HTML is a markup language, which may sound complicated, although really you come across markup every day. Markup is just something you add to a document to give it special meaning; for example, when you use a highlighter pen you are marking up a document. When you are marking up a document for the Web, the special meaning you are adding indicates the structure of the document, and the markup indicates which part of the document is a heading, which parts are paragraphs, what belongs in a table, and so on. This markup in turn allows a Web browser to display your document appropriately.

When creating a document in a word processor, you can distinguish headings using a heading style (usually with a larger font) to indicate which part of the text is a heading. You can use the Enter (or Return) key to start a new paragraph. You can insert tables into your document, create bulleted lists,
and so on. When marking documents up for the Web you are performing a very similar process. HTML and XHTML are the languages you use to tell aWeb browser where the heading is for aWeb page, what is a paragraph, what is part of a table and so on, so it can structure your document and render it properly. But what is the difference between HTML and XHTML?Well, first you should know that there are several versions of both HTML and XHTML, but don’t let that bother you—it all sounds a lot more complicated than it really is. Whereas there are several versions of HTML, each version just adds functionality on top of its predecessor (like a new version of some software might add some features or a new version of a dictionary might add a few extra words), or offers better ways of doing things that were already in earlier versions. So, you do not need to learn each version of HTML and XHTML, nor do you need to focus on one variation. This book teaches you all you need to know to writeWeb pages using HTML and XHTML. Indeed, as I mentioned in the Introduction, XHTML is just like the latest version of HTML, as you will see shortly (although to be accurate, while it is almost identical to the last version of HTML, it is technically HTML’s successor).

Sample Code :

<html>
<head>
<title>Vdiscussion: About Us</title>
</head>
<body>
<h1>About Vdiscussion.com</h1>
<p>Vdiscussion is free educational site
</p>
</body>
</html>

Save this code as filename.html.