Tuesday, 6 January 2015

PHP String Functions

 PHP String Functions


PHP string functions are used to manipulate string data

Addslashes : 
Adds slashes to specified characters in a string.is used to add slashes to certain characters in a string. Those characters are single quote ('), double quote ("), and the NULL character. This function is useful when we try to insert strings into a database.
while inserting into database its easy..

Example:
echo $returnValue = addslashes("test function's");

Output
test function\'s


Explode: 
The explode function in PHP is used to split a string into multiple strings based on the specified delimiter.

Example:
1.     print_r (explode (',','one,two,three'));
2.     print_r (explode (',','one,two,three',2));
3.     $var = 'Learn PHP'; 
        print_r (explode (' ',$var));

Output
1.     Array ( [0] => one [1] => two [2] => three ) 
2.     Array ( [0] => one [1] => two,three )
3.     Array ( [0] => Learn [1] => PHP )
similar functions:
preg_split, str_split, mb_split, str_word_count, strtok, implode


implode : 
Join array elements into string.

Example:
$returnVal = array('Peter','Ben','Sat','Lol');
echo implode('+', $returnVal );;

Output
Peter+Ben+Sat+Lol
similar functions:
explode, preg_split, http_build_query


htmlentities
Converts all applicable characters to HTML entities.
Example:
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;

echo htmlentities($str, ENT_QUOTES);
similar functions:
html_entity_decode, get_html_translation_table, htmlspecialchars, nl2br, urlencode

 htmlspecialchars
Converts special characters to HTML entities.
Example:
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);

echo $new; 
Outputs:
 &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

md5
Calculates the md5 hash of a string.
Example:
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";

}

similar functions:
 md5_file, sha1_file, crc32, sha1, hash

number_format
Sets the format of a numerical output.
Example:
$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');

// 1234.57

print
Outputs one or more strings.
Example:
1.print("Hello World");
2.print "print() also works without parentheses.";
3.print "escaping characters is done \"Like this\".";
// You can use variables inside a print statement
$foo = "foobar";
$bar = "barbaz";
4.print "foo is $foo"; // foo is foobar
// You can also use arrays
$bar = array("value" => "foo");
5.print "this is {$bar['value']} !"; // this is foo !
// If you are not using any other characters, you can just print variables

6.print $foo;          // foobar

similar functions:
 echo, printf, flush
PRINTF : Output a formatted string.
FLUSH : Flush the output buffer
ECHO : Output one or more strings.

str_replace
Changes certain occurrances on a string with a replacement string.
syntax   :   str_replace(search, replace, subject);

Example:
echo $var = str_replace("search", "hai", "subject search");
Output: subject hai

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
echo $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
Output:Hll Wrld f PHP

$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
Output:   2
similar functions:
 str_ireplace, substr_replace, preg_replace, strtr

strlen
Returns the length of a string.
Example:
$str = 'abcdef';
echo strlen($str);                 Output:  6

$str = ' ab cd ';

echo strlen($str);                 Output:  7
similar functions:
 count, mb_strlen

strpos
Finds the position of the first match in a string.
syntax:   strpos(haystack, needle);
Example:
$mystring = 'abc';
$findme   = 'b';
echo $pos = strpos($mystring, $findme);

Output
2  //2nd position
similar functions:
stripos, strrpos, strripos, strstr, strpbrk, substr, preg_match

 strstr
Find the first occurrence of a string.
syntax:   strpos(haystack, needle);
Example:
$email  = 'name@example.com';
echo $domain = strstr($email, '@');            Output @example.com

$user = strstr($email, '@', true); 
echo $user;                                                 Output:  name

substr
 Retrieves a portion of the string.
Example:
echo $rest = substr("abcdef", -1);       Output :        f
echo $rest = substr("abcdef", -2);       Output :        ef
echo $rest = substr("abcdef", -3, 1);   Output :         d
similar functions:
strrchr, trim, wordwrap

 trim

 Strips out white spaces  from the beginning and end of a string.
similar functions:
ltrim, rtrim, str_replace
 
sort() -
sort arrays in ascending order. asort() - sort associative arrays in ascending order, according to the value.
ksort() -
sort associative arrays in ascending order, according to the key.
arsort() -
sort associative arrays in descending order, according to the value.
rsort() -
sort arrays in descending order.
krsort() -
sort associative arrays in descending order, according to the key.
array_multisort() -
sort the multi dimension array.
usort()-
Sort the array using user defined function.

Friday, 2 January 2015

PHP Predefined variables

 PHP Predefined variables

sample URL like and after submit
 http://localhost/test.php  -->   http://localhost/result.php?id=21

Server variables: $_SERVER : Server and execution environment information.


$_SERVER['PHP_SELF']                            output : /result.php

$_SERVER['GATEWAY_INTERFACE']         output :CGI/1.1

$_SERVER['SERVER_ADDR']                     output : 127.0.0.1

$_SERVER['REMOTE_ADDR']                output :  127.0.0.1

$_SERVER['SERVER_NAME']                     output : localhost

$_SERVER['HTTP_HOST']                       output :  localhost

$_SERVER['SERVER_SOFTWARE']             output : Apache/2.2.17 (Win32) PHP/5.3.4

$_SERVER['HTTP_CONNECTION']         output : keep-alive 

$_SERVER['SERVER_PROTOCOL']             output : HTTP/1.1

$_SERVER['SERVER_ADMIN']               output : admin@localhost

$_SERVER['REQUEST_METHOD']              output : POST/ GET

$_SERVER['SERVER_PORT ']                  output : 80

$_SERVER['REQUEST_TIME']                    output :1420187992

$_SERVER['QUERY_STRING']                    output : id=21

$_SERVER['REQUEST_URI']                    output :  /result.php?id=21

$_SERVER['SCRIPT_NAME']                    output :/result.php

$_SERVER['SCRIPT_FILENAME']            output : C:/wamp/www/result.php

$_SERVER['DOCUMENT_ROOT']            output :  C:/wamp/www/

$_SERVER['HTTP_REFERER']                outputhttp://localhost/test.php (previous page)

$_SERVER['DOCUMENT_ROOT']          output :  C:/wamp/www/

$GLOBALS   : Global variables References all variables available in global scope.

Example: 
$x = 75;           $y = 25; 
function addition() { 
    $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; 
}
addition(); 
echo $z; 

Output:
100

$_GET: HTTP GET variables.

URL like and after submit
 http://localhost/test.php  -->   http://localhost/result.php?id=21
$_GET['id'] 

Output :  21


$_POST: HTTP POST variables.

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>


$_FILES: HTTP File Upload variables.

An associative array of items uploaded to the current script via the HTTP POST method


$_REQUEST: HTTP Request variables.

Example: 
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_REQUEST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

$_SESSION: Session variables.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit

Example:
<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>
Output
You have visited this page 1in this session.
(after refresh )
You have visited this page 2in this session.......

$_COOKIE: HTTP Cookies.

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

setcookie(name, value, expire, path, domain, security);

Example:
   setcookie("name", "John Watkin", time()+3600, "/","", 0);
   setcookie("age", "36", time()+3600, "/", "",  0);

Output
Set Cookies John Watkin
36