Posts Tagged ‘php’

Fairywren welcomes you to this site..
“If you find it useful then please promote or share it. Its giving me encourage to post on new topics.”-admin@myfairywren.
Regular Expressions Tutorial:
Another simple tutorial for novice PHP programmer.

I have searched the web far and near for a good tutorial on PHP Regular Expressions
and I have come up with a multitude of sites. However, I needed just a little bit of
information from each of the sites and I ended up trying to move between 10 different
webpages to get the information I needed at a particular time. This tutorial is a
collation of all those bits of information. Some of this is my work, but it is mostly
good collection of other tutorials available out there. In order to give authors credit
for their work, I have included ALL the links of those pages and if anyone feels like
this is an outrage, let me know and I will take down the relevant information.
So here goes…
Basic Syntax of Regular Expressions (as from PHPBuilder.com)
First of all, let’s take a look at two special symbols: ‘^’ and ‘$’. What they do is indicate the
start and the end of a string, respectively, like this:

“^The”: matches any string that starts with “The”;
“of despair$”: matches a string that ends in the substring “of despair”;
“^abc$”: a string that starts and ends with “abc” — that could only be “abc” itself!
“notice”: a string that has the text “notice” in it.
You can see that if you don’t use either of the two characters we mentioned, as in the last example,
you’re saying that the pattern may occur anywhere inside the string — you’re not “hooking” it to any of the edges.

There are also the symbols ‘*’, ‘+’, and ‘?’, which denote the number of times a character or a sequence of
characters may occur. What they mean is: “zero or more”, “one or more”, and “zero or one.” Here are some examples:

“ab*”: matches a string that has an a followed by zero or more b’s (“a”, “ab”, “abbb”, etc.);
“ab+”: same, but there’s at least one b (“ab”, “abbb”, etc.);
“ab?”: there might be a b or not;
“a?b+$”: a possible a followed by one or more b’s ending a string.
You can also use bounds, which come inside braces and indicate ranges in the number of occurences:

“ab{2}”: matches a string that has an a followed by exactly two b’s (“abb”);
“ab{2,}”: there are at least two b’s (“abb”, “abbbb”, etc.);
“ab{3,5}”: from three to five b’s (“abbb”, “abbbb”, or “abbbbb”).
Note that you must always specify the first number of a range (i.e, “{0,2}”, not “{,2}”). Also, as you might
have noticed, the symbols ‘*’, ‘+’, and ‘?’ have the same effect as using the bounds “{0,}”, “{1,}”, and “{0,1}”,
respectively.

Now, to quantify a sequence of characters, put them inside parentheses:

“a(bc)*”: matches a string that has an a followed by zero or more copies of the sequence “bc”;
“a(bc){1,5}”: one through five copies of “bc.”
There’s also the ‘|’ symbol, which works as an OR operator:

“hi|hello”: matches a string that has either “hi” or “hello” in it;
“(b|cd)ef”: a string that has either “bef” or “cdef”;
“(a|b)*c”: a string that has a sequence of alternating a’s and b’s ending in a c;
A period (‘.’) stands for any single character:

“a.[0-9]”: matches a string that has an a followed by one character and a digit;
“^.{3}$”: a string with exactly 3 characters.
Bracket expressions specify which characters are allowed in a single position of a string:

“[ab]”: matches a string that has either an a or a b (that’s the same as “a|b”);
“[a-d]”: a string that has lowercase letters ‘a’ through ‘d’ (that’s equal to “a|b|c|d” and even “[abcd]”);
“^[a-zA-Z]”: a string that starts with a letter;
“[0-9]%”: a string that has a single digit before a percent sign;
“,[a-zA-Z0-9]$”: a string that ends in a comma followed by an alphanumeric character.
You can also list which characters you DON’T want — just use a ‘^’ as the first symbol in a bracket expression
(i.e., “%[^a-zA-Z]%” matches a string with a character that is not a letter between two percent signs).

In order to be taken literally, you must escape the characters “^.[$()|*+?{\” with a backslash (‘\’), as
they have special meaning. On top of that, you must escape the backslash character itself in PHP3 strings, so,
for instance, the regular expression “(\$|¥)[0-9]+” would have the function call: ereg(“(\\$|¥)[0-9]+”, $str)
(what string does that validate?)

Example 1. Examples of valid patterns

* //

* |(\d{3})-\d+|Sm

* /^(?i)php[34]/

* {^\s+(\s+)?$}

Example 2. Examples of invalid patterns

* /href='(.*)’ – missing ending delimiter

* /\w+\s*\w+/J – unknown modifier ‘J’

* 1-\d3-\d3-\d4| – missing starting delimiter

Some useful PHP Keywords and their use (php.net man pages)

preg_split

(PHP 3>= 3.0.9, PHP 4 )
preg_split — Split string by a regular expression
Description
array preg_split ( string pattern, string subject [, int limit [, int flags]])

Returns an array containing substrings of subject split along boundaries matched by pattern.

If limit is specified, then only substrings up to limit are returned, and if limit is -1, it
actually means “no limit”, which is useful for specifying the flags.

flags can be any combination of the following flags (combined with bitwise | operator):

PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().

PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and
returned as well. This flag was added for 4.0.5.

PREG_SPLIT_OFFSET_CAPTURE
If this flag is set, for every occuring match the appendant string offset will also be
returned. Note that this changes the return value in an array where every element is an
array consisting of the matched string at offset 0 and it’s string offset into subject
at offset 1. This flag is available since PHP 4.3.0 .

Example 1. preg_split() example : Get the parts of a search string

Example 2. Splitting a string into component characters

Example 3. Splitting a string into matches and their offsets

will yield:

Array
(
[0] => Array
(
[0] => hypertext
[1] => 0
)

[1] => Array
(
[0] => language
[1] => 10
)

[2] => Array
(
[0] => programming
[1] => 19
)

)

Note: Parameter flags was added in PHP 4 Beta 3.

preg_match

(PHP 3>= 3.0.9, PHP 4 )
preg_match — Perform a regular expression match
Description
int preg_match ( string pattern, string subject [, array matches [, int flags]])

Searches subject for a match to the regular expression given in pattern.

If matches is provided, then it is filled with the results of search. $matches[0] will
contain the text that matched the full pattern, $matches[1] will have the text that matched
the first captured parenthesized subpattern, and so on.

flags can be the following flag:

PREG_OFFSET_CAPTURE
If this flag is set, for every occuring match the appendant string offset will also
be returned. Note that this changes the return value in an array where every element
is an array consisting of the matched string at offset 0 and it’s string offset into
subject at offset 1. This flag is available since PHP 4.3.0 .

The flags parameter is available since PHP 4.3.0 .

preg_match() returns the number of times pattern matches. That will be either 0 times
(no match) or 1 time because preg_match() will stop searching after the first match.
preg_match_all() on the contrary will continue until it reaches the end of subject.
preg_match() returns FALSE if an error occured.

Tip: Do not use preg_match() if you only want to check if one string is contained
in another string. Use strpos() or strstr() instead as they will be faster.

Example 1. Find the string of text “php”

Example 2. Find the word “web”

Example 3. Getting the domain name out of a URL

This example will produce:

domain name is: php.net

Perl Style Delimiters (as from crazygrrl.com)

When using Perl-style matching, the pattern also has to be enclosed by special delimiters.
The default is the forward slash, though you can use others. For example:

/colou?r/

Usually you’ll want to stick with the default, but if you need to use the
forward slash a lot in the actual pattern (especially if you’re dealing with
pathnames) you might want to use something else:

!/root/home/random!

To make a match case-insensitive, all you need to do is append the option
i to the pattern:

/colou?r/i

Perl-style functions support these extra metacharacters (this is not a full
list):

\b A word boundary, the spot between word (\w) and non-word (\W) characters.
\B A non-word boundary.
\d A single digit character.
\D A single non-digit character.
\n The newline character. (ASCII 10)
\r The carriage return character. (ASCII 13)
\s A single whitespace character.
\S A single non-whitespace character.
\t The tab character. (ASCII 9)
\w A single word character – alphanumeric and underscore.
\W A single non-word character.

Example:

/\bhomer\b/

Have a donut, Homer no match
A tale of homeric proportions! no match
Do you think he can hit a homer? match

Corresponding to ereg() is preg_match(). Syntax:

preg_match(pattern (string), target (string), optional_array);

Example:

$pattern = “/\b(do(ugh)?nut)\b.*\b(Homer|Fred)\b/i”;

$target = “Have a donut, Homer.”;

if (preg_match($pattern, $target, $matches)) {

print(“

Match: $reg[0]

“);
print(“

Pastry: $reg[1]

“);
print(“

Variant: $reg[2]

“);
print(“

Name: $reg[3]

“);
}

else {
print(“No match.”);
}

Results:

Match: donut, Homer

Pastry: donut

Variant: [blank because there was no “ugh”]

Name: Homer

If you use the $target “Doughnut, Frederick?” there will be no match,
since there has to be a word boundary after Fred.

but “Doughnut, fred?” will match since we’ve specified it to be
case-insensitive.

Contributed code which is applicable (and very useful!)
mkr at binarywerks dot dk
A (AFAIK) correct implementation of Ipv4 validation, this one supports optional ranges
(CIDR notation) and it validates numbers from 0-255 only in the address part, and 1-32
only after the /

<?

function valid_ipv4($ip_addr)
{
$num="([0-9]|1?\d\d|2[0-4]\d|25[0-5])";
$range="([1-9]|1\d|2\d|3[0-2])";

if(preg_match("/^$num\.$num\.$num\.$num(\/$range)?$/",$ip_addr))
{
return 1;
}

return 0;
}

$ip_array[] = "127.0.0.1";
$ip_array[] = "127.0.0.256";
$ip_array[] = "127.0.0.1/36";
$ip_array[] = "127.0.0.1/1";

foreach ($ip_array as $ip_addr)
{
if(valid_ipv4($ip_addr))
{
echo "$ip_addr is valid
\n”;
}
else
{
echo “$ip_addr is NOT valid
\n”;
}
}

?>

plenque at hotmail dot com
I wrote a function that checks if a given regular expression is valid. I think some of
you might find it useful. It changes the error_handler and restores it, I didn’t find
any other way to do it.

Function IsRegExp ($sREGEXP)
{
$sPREVIOUSHANDLER = Set_Error_Handler (“TrapError”);
Preg_Match ($sREGEXP, “”);
Restore_Error_Handler ($sPREVIOUSHANDLER);
Return !TrapError ();
}

Function TrapError ()
{
Static $iERRORES;

If (!Func_Num_Args ())
{
$iRETORNO = $iERRORES;
$iERRORES = 0;
Return $iRETORNO;
}
Else
{
$iERRORES++;
}
}

PHP Get_title tag code which uses simple regex and nice php string functions
(As from Zend PHP)

<?php
function get_title_tag($chaine){
$fp = fopen ($chaine, 'r');
while (! feof ($fp)){
$contenu .= fgets ($fp, 1024);
if (stristr($contenu, '’ )){
break;
}
}
if (eregi(“”, $contenu, $out)) {
return $out[1];
}
else{
return false;
}
}
?>

My Own ‘Visitor Trac’ code which uses regex XML parsing methods

7) {
unlink($filename);
$fp = fopen($filename, “a”);
}
else $fp = fopen($filename, “a”);
}
else $fp = fopen($filename, “a”);
if (!$_SERVER[‘HTTP_REFERER’]) $url_test = ‘http://dinki.mine.nu/weblog/&#8217;;
else $url_test = $_SERVER[‘HTTP_REFERER’];
$new_title = return_title ($url_test);
//print $new_title;
$new_name = stripslashes(“$new_title\n”);
$new_URL = stripslashes(“$referer\n”);
fwrite($fp,$new_URL);
fwrite($fp,$new_name);
fclose($fp);

$fp = fopen($filename, “r”);
$file = implode(”, file ($filename));
$foo = preg_split(“//”,$file);
$number = count($foo);
//print $number;
if ($number > 11) {
fclose($fp);
$fp = fopen($filename, “w”);
$count = $number – 10;
while ($count < $number) {
$print1 = $foo[$count];
$print2 = $foo[$count+1];
print " “;
print “$print2“; //print $count;
$count += 2;
$new_name = stripslashes(“$print2”);
$new_URL = stripslashes(“$print1”);
fwrite($fp,$new_URL);
fwrite($fp,$new_name);
}
fclose($fp);
}
//print_r($foo);
else {
$count = 1;
while ($count <= $number) {
$print1 = $foo[$count];
$print2 = $foo[$count+1];
print " “;
print “$print2“; //print $count;
$count += 2;
}
fclose($fp);
}

function return_title($url) {
print $filename.” “.$difference;
$array = file ($url);
for ($i = 0; $i < count($array); $i++)
{
if (preg_match("/(.*)/i”,$array[$i], $tag_contents)) {
$title = $tag_contents[1];
$title = strip_tags($title);
}
}
return $title;
}

?>
Special Thanks to http://weblogtoolscollection.com

Generating Random Numbers Within a Range in PHP by Mrinmoy

Problem-You want to generate a random number within a range of numbers.
Solution-Use mt_rand();
The proper syntax is > $random_number = mt_rand($lower,$upper);
Discussion:
Generating random numbers is useful when you want to display a random image on a page, randomize the starting point of a game, select a random record from a database , or generate a unique session identifier.

Calling mt_rand() without any arguments it returns any random numbr between 0 to maximum random number which we can easily get using mt_getrandmax().
Generating truly random number is very difficult for any computer. Computers excel at following instructions methodically; they’re not so good at spontaneity. If you want to instruct a computer to return random numbers, you need to give it a specific set of commands; the very fact that they are repeatable undermines the desired randomness.
PHP has two different random number generator one is rand() and another is mt_rand().
In my view mt_rand() is better. mt_rand () is more faster and accurate random number generator.

Okay I think you already take this lesson completely..IF you are not please inform me..I will help you to understand it.
Otherwise you can check these following link for more details:
Details about mt_rand() on php.net
mt_rand() on w3schools

Example:
<?php
$random_number=mt_rand(1,100);
echo $random_number;
echo "mt_rand(100,200)";
?>

The output will be like this:
12 //——>Random Number between 1 to 100
145 //——>Random Number between 100 to 200

We will cover next session soon..stay connected…–>iMrinmoy

Strings

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

Note: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.

Syntax

A string literal can be specified in four different ways:

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ).

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<!--?php
echo 'this is a simple string';
echo ‘You can also have embedded newlines in
strings this way as it is
okay to do’;

// Outputs: Arnold once said: “I’ll be back”
echo ‘Arnold once said: “I\’ll be back”‘;

// Outputs: You deleted C:\*.*?
echo ‘You deleted C:\\*.*?’;

// Outputs: You deleted C:\*.*?
echo ‘You deleted C:\*.*?’;

// Outputs: This will not expand: \n a newline
echo ‘This will not expand: \n a newline’;

// Outputs: Variables do not $expand $either
echo ‘Variables do not $expand $either’;
?>

Double quoted

If the string is enclosed in double-quotes (“), PHP will interpret more escape sequences for special characters:

Escaped characters
Sequence Meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\” double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

WarningIt is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It’s also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.

If this rule is broken and the closing identifier is not “clean”, it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Example #1 Invalid example

<!--?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Example #2 Heredoc string quoting example

<!--?php
$str = <<
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;

function foo()
{
$this->foo = ‘Foo’;
$this->bar = array(‘Bar1’, ‘Bar2’, ‘Bar3’);
}
}

$foo = new foo();
$name = ‘MyName’;

echo <<<EOT
My name is “$name”. I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital ‘A’: \x41
EOT;
?>

The above example will output:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

It is also possible to use the Heredoc syntax to pass data to function arguments:

Example #3 Heredoc in arguments example

<!--?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>

As of PHP 5.3.0, it’s possible to initialize static variables and class properties/constants using the Heredoc syntax:

Example #4 Using Heredoc to initialize static values

<!--?php
// Static variables
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}
// Class properties/constants
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;

public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:

Example #5 Using double quotes in Heredoc

<!--?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Note:

Heredoc support was added in PHP 4.

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <!–[CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<‘EOT’. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example #6 Nowdoc string quoting example

<!--?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
public $foo;
public $bar;

function foo()
{
$this->foo = ‘Foo’;
$this->bar = array(‘Bar1’, ‘Bar2’, ‘Bar3’);
}
}

$foo = new foo();
$name = ‘MyName’;

echo <<<‘EOT’
My name is “$name”. I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital ‘A’: \x41
EOT;
?>

The above example will output:

My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

Note:

Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:

Example #7 Static data example

<!--?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>

Note:

Nowdoc support was added in PHP 5.3.0.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<!--?php
$juice = "apple";
echo “He drank some $juice juice.”.PHP_EOL;
// Invalid. “s” is a valid character for a variable name, but the variable is $juice.
echo “He drank some juice made of $juices.”;
?>

The above example will output:

He drank some apple juice.
He drank some juice made of .

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

Example #8 Simple syntax example

<!--?php
$juices = array("apple", "orange", "koolaid1" => "purple");
echo “He drank some $juices[0] juice.”.PHP_EOL;
echo “He drank some $juices[1] juice.”.PHP_EOL;
echo “He drank some juice made of $juice[0]s.”.PHP_EOL; // Won’t work
echo “He drank some $juices[koolaid1] juice.”.PHP_EOL;

class people {
public $john = “John Smith”;
public $jane = “Jane Smith”;
public $robert = “Robert Paulsen”;

public $smith = “Smith”;
}

$people = new people();

echo “$people->john drank some $juices[0] juice.”.PHP_EOL;
echo “$people->john then said hello to $people->jane.”.PHP_EOL;
echo “$people->john’s wife greeted $people->robert.”.PHP_EOL;
echo “$people->robert greeted the two $people->smiths.”; // Won’t work
?>

The above example will output:

He drank some apple juice.
He drank some orange juice.
He drank some juice made of s.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .

For anything more complex, you should use the complex syntax.

Complex (curly) syntax

This isn’t called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<!--?php
// Show all errors
error_reporting(E_ALL);
$great = ‘fantastic’;

// Won’t work, outputs: This is { fantastic}
echo “This is { $great}”;

// Works, outputs: This is fantastic
echo “This is {$great}”;
echo “This is ${great}”;

// Works
echo “This square is {$square->width}00 centimeters broad.”;

// Works, quoted keys only work using the curly brace syntax
echo “This works: {$arr[‘key’]}”;

// Works
echo “This works: {$arr[4][3]}”;

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo “This is wrong: {$arr[foo][3]}”;

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo “This works: {$arr[‘foo’][3]}”;

// Works.
echo “This works: ” . $arr[‘foo’][3];

echo “This works too: {$obj->values[3]->name}”;

echo “This is the value of the var named $name: {${$name}}”;

echo “This is the value of the var named by the return value of getName(): {${getName()}}”;

echo “This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}”;

// Won’t work, outputs: This is the return value of getName(): {getName()}
echo “This is the return value of getName(): {getName()}”;
?>

It is also possible to access class properties using variables within strings using this syntax.

<!--?php
class foo {
var $bar = 'I am bar.';
}
$foo = new foo();
$bar = ‘bar’;
$baz = array(‘foo’, ‘bar’, ‘baz’, ‘quux’);
echo “{$foo->$bar}\n”;
echo “{$foo->$baz[1]}\n”;
?>

The above example will output:

I am bar.
I am bar.

Note:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

<!--?php
// Show all errors.
error_reporting(E_ALL);
class beers {
const softdrink = ‘rootbeer’;
public static $ale = ‘ipa’;
}

$rootbeer = ‘A & W’;
$ipa = ‘Alexander Keith\’s’;

// This works; outputs: I’d like an A & W
echo “I’d like an {${beers::softdrink}}\n”;

// This works too; outputs: I’d like an Alexander Keith’s
echo “I’d like an {${beers::$ale}}\n”;
?>

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

WarningWriting to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NULL byte.

Example #9 Some string examples

<!--?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
// Get the third character of a string
$third = $str[2];

// Get the last character of a string.
$str = ‘This is still a test.’;
$last = $str[strlen($str)-1];

// Modify the last character of a string
$str = ‘Look at the sea’;
$str[strlen($str)-1] = ‘e’;

?>

Note:

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

Useful functions and operators

Strings may be concatenated using the ‘.’ (dot) operator. Note that the ‘+’ (addition) operator will not work for this. See String operators for more information.

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, see also the character type functions.

Converting to string

A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo() or print() functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A boolean TRUE value is converted to the string “1”. Boolean FALSE is converted to “” (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

Note:

The decimal point character is defined in the script’s locale (category LC_NUMERIC). See the setlocale() function.

Arrays are always converted to the string “Array”; because of this, echo() and print() can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr[‘foo’]. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string “Object”. To print the values of object properties for debugging reasons, read the paragraphs below. To get an object’s class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure “Resource id #1”, where 1 is the unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. To get a resource‘s type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters ‘.’, ‘e’, or ‘E’ and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an ‘e’ or ‘E’ followed by one or more digits.

<!--?php
$foo = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;          // $foo is float (11)
$foo = "10.0 pigs " + 1.0;        // $foo is float (11)
?>

For more information on this conversion, see the Unix manual page for strtod(3).

To test any of the examples in this section, cut and paste the examples and insert the following line to see what’s going on:

<!--?php
echo "\$foo==$foo; type is " . gettype ($foo) . "
\n";
?>

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.

Details of the String Type

The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)

This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.

Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string “á” equivalent to “\xE1” (ISO-8859-1), “\xC3\xA1” (UTF-8, C form), “\x61\xCC\x81” (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicity declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic.

Of course, in order to useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:

  • Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets.
  • Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities() and the majority of the functions in the mbstring extension.
  • Others use the current locale (see setlocale()), but operate byte-by-byte. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper(“á”) may return “Á” if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale.
  • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding.

Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.

Scalar data

Scalar data can hold only one value at a time. PHP knows four different types of scalar data:
Boolean: possible values are TRUE or FALSE
[ad]int: can be any signed (so both positive and negative values are possible) numeric integer value
float: can be any signed (so both positive and negative values are possible) floating-point value
string: can be any collection of binary data

Numeric values
Numeric values can be both of the type integer as floating point, and can be annotated in decimal, octal (identified by leading zero) or hexadecimal (identified by leading 0x), and for floating-popint numbers, they can be annotated in decimal and exponential (2E7, 2.3E5).
A very important thing to note when working with numbers i s that the precision and the range of your data types depends on the machine you are working on. For instance, & 64-bit system will have a wider range than a 32-bit system. Also, PHP doesn’t track overflows. So stuffing your variable with too much data will NOT throw an error, but will result in a truncated value.
Another thing to keep in mind is that floats are not always storing their value the way you would think. For example, if you execute the statement

integervar (int) (0.2 + 0.4) * 10);
print integervar;

The printed result will not be 6 as you would expect, but it will be 5. This is because the result of 0.2 and 0.4 is not stored as 0.6 in the float, but as 0.59999999, and times ten, this gives 5.999999
When this float is conversed to an int, it simply truncates everyting behind the fraction, resulting in 5.
These things are not necessarily a disaster, but are limitations you should be aware of when doing calculations in your PHP code.

Strings
When talking about strings, most programmers immediately think of text. This is indeed the case. In some languages. Not in PHP, oh no. In PHP, a string is an ordered collection of binary data. This data can be text, but can also be an image, an office document, or a mp3-file.
Due to the extended character of strings, and all that is possible with them in PHP, we will get back on them later.

Booleans
Booleans are the easiest of all variables, as they can only hold one of two values: true or false, and are therefor mostly used in logical operations.
There are some important things to know about booleans and conversions though:
When you convert any number (no matter if it is an integer or a float) to a boolean, the boolean will always be true, except when the value of the number is zero.
When you convert a string to a boolean, the boolean will always be true, except when the string is empty (null), or contains a single digit 0 (zero). When there are multiple zeros in the string (00000), the boolean will convert to true.
When you convert a boolean to a string, integer or float, the value will be 1 if the boolean was true, and 0 if the boolean is false.

Composite Data

PHP doesn’t only support the scalar data types we discussed above, but also supports two compound or composite datatypes. The name compound or somposite comes from the fact that they are in essence containers of other data.

Arrays
Arrays contain data of other datatypes in an ordered way. Arrays can contain any of the abovementioned scalar data. We will digg deeper into arrays in a future lesson.

Objects
Objects contain both data and code. Objects are the cornerstones of Object Oriented Programming (OOP) (who would’ve thought, right?), and are also dugg into in a future lesson.

Special Data Types

Besides the two data types we mentioned above, there are also two very special data types:

NULL
Null indicates that a variable has no value. A variable can get the NULL value by getting it specifically assigned, or by not yet having been assigned any value at all.

Resource
The resource data type is used when dealing with external resources that are not part of PHP, but are used inside your code, for example a file.

Converting between data types

PHP is very easy when it comes to converting data types, as it does all the work for you, for free! However, if you really want to convert a variable to another data type yourself, you can do this by putting the name of the data type you want to convert to between parentheses, and place it in front of the expression or variable you want to convert. Check it out, it was already there in the example we used before:

integervar (int) (0.2 + 0.4) * 10);

• Applet
• Macromedia Flash/Air
• Java WebStart
• DHTML
• DHTML with Hidden IFrame
• Ajax
• Sliverlight (Windows only)
• JavaFX (Java Platform)
To read more: