Archive for the ‘Strings’ Category

Convert array to string

Friday, October 19th, 2007

Problem: You want to convert an array to string so that it is easier to print the result instead of looping inside the array and have this printed

Old Solution:

$aArr = array("Have you ever seen",
"the beauty of the world.",
"The wonderful creation of the Lord." );
foreach($aArr as $sString) {
    print $sString;
}

Other Solution:

$aArr = array("Have you ever seen",
"the beauty of the world.",
"The wonderful creation of the Lord." );
$sString = implode(" ", $aArr);
print $sString;

In Action: I want to execute a linux command via PHP and get its result and extract the desire content. The example below will try to extract the ip address from the ifconfig command

exec("ifconfig", $aOutput);
$sTempString = implode(" ", $aOutput);
preg_match("/inet\saddr:(.*?)\s/i", $sTempString, $aMatch);
print $aMatch[1]; //

Getting a single character in a string

Tuesday, October 9th, 2007

This snippet of code will show how to get individual character from a string in a variable

$sMyName = “Darwin”;

print $sMyName[1]; // will print the letter “a”

How to use heredoc in PHP

Tuesday, October 9th, 2007

Heredoc also known as here-document is a way of specifying string literals or printing them literally without the use of quotes to threat them as literal strings. Heredoc preserves the line breaks and other whitespace (including indentation) in the text.

Heredocs start with <<< and a token or also known as delimiting identifier. The token or delimiting identifier don’t leading or trailing whitespace and followed by semicolon a to end the statement.

Example: We wanted to print this string

The quick brown fox
jumps over the lazy dog.
But what is the name of that dog 
whom the fox jumped over.

Usually we will use the print built in function of php and put line breaks to separate the lines

print "The quick brown fox \n";
print "jumps over the lazy dog. \n";
print "But what is the name of that dog \n"; 
print "whom the fox jumped over \n";

In heredoc we literally print these sequence string without having to print all the lines 1 by 1;

Using heredoc

print <<< DOGS
The quick brown fox
jumps over the lazy dog.
But what is the name of that dog 
whom the fox jumped over.
DOGS; 

Heredocs in HTML

$sAnimal = "cat";
$aZoo = array("elephant","zebra","monkey","lion","bear");
print <<< ZOO
There are different animals in the zoo.
It includes <b>$aZoo[1], $aZoo[3].</b>
There are also <font color="red">$sAnimal</font> here.
ZOO;