Friday, 6 November 2015

PHP String Functions & CONSTANT

02:03

PHP String Functions :

Get The Length of a String:
The PHP strlen() function returns the length of a string (number of characters).
The example below returns the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>

Output:
12


Count The Number of Words in a String
The PHP str_word_count() function counts the number of words in a string:
<?php

echo str_word_count("Hello world!"); // outputs 2

?>
Output :
2

Reverse a String
The PHP strrev() function reverses a string:
<?php

echo strrev("Hello world!");   // outputs !dlrow olleH

?>
Output:
!dlrow olleH


without using strrev()  write code of php using for loop:


<?php
$string = "sandep";
$len = strlen($string);
for($i=$len; $i > 0; $i--)
{
    echo $string[$i-1];
}


?>

output:
pednas

Search For a Specific Text Within a String
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
<?php

echo strpos("Hello world!", "world"); // outputs 6

?>
Output:
6

Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.
The example below replaces the text "world" with "Dolly":
<?php

echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!

?>

Hello Dolly!




================================================================


PHP strtolower() Function :
PHP String Reference PHP String Reference
Convert all characters to lowercase:

Example  :

<?php
echo strtolower("Hello WORLD.");
?>




PHP strtoupper() Function :
PHP String Reference PHP String Reference
Convert all characters to uppercase:

Example :

<?php
echo strtoupper("Hello WORLD!");
?>


PHP lcfirst() Function:
PHP String Reference PHP String Reference
Convert the first character of "Hello" to lowercase:

Example :

<?php
echo lcfirst("Hello world!");
?>




PHP ucfirst() Function :
PHP String Reference PHP String Reference
Convert the first character of "hello" to uppercase:

Example :

<?php
echo ucfirst("hello world!");
?>



PHP ucwords() Function :
PHP String Reference PHP String Reference
Convert the first character of each word to uppercase:

Example :

<?php
echo ucwords("hello world");

?>

========================================================================
use PHP stristr function to match the beginning of a string:
========================================================================
<?php
$pageURL = $_SERVER['REQUEST_URI'];
$myurl   = 'om.php';

if (stristr($pageURL, $myurl) !== FALSE) {
    echo '<script >  alert("it is popup") </script>';
} else {
    echo "wrong";
}

?>

note : when you will run above it will  alert you with popup window ..


The substr() function returns a part of a string.
Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.

Syntax:

substr(string,start,length)

Example:

(1)write code for  substr.html(enter digit "123" ) :

<form action=substr.php   method=post>
enter your 3 digit number<input type=text name=number>
<input type=submit  name=submit  value=submit>
</form>

(2)write code for substr.php :

<?php

$a=$_POST['number'];

$b=substr($a,0,1);

$c=substr($a,1,1);

$d=substr($a,2,1);


echo "value of b=".$b.'<Br>';
echo "value of c=".$c.'<br>';
echo "value of d=".$d.'<br>';

echo $b+$d;

?>
output:
1
2
3
4

==============================================================================================================================================
Simple   PHP   Application   to  save website content from a  website to  a file then make search to that file:

Step 1:   store   website  content   to a file  code given below :

<?php

  $curl_handle=curl_init();
 
  curl_setopt($curl_handle,CURLOPT_URL,'http://www.vissicomp.com');
 
  curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
 
  curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
 
  $buffer = curl_exec($curl_handle);
 
  $fhandle=fopen("example.txt","a");
fwrite($fhandle,$buffer);
 
  curl_close($curl_handle);
 
  if (empty($buffer))
{
      print "Nothing returned from url.<p>";
  }
 
  else
{

      print $buffer;

  }
?>


Step 2 make Search in that file for particular word:

(a)write code for search.html:

<form action=searchst.php   method=post>
<input type=text name=search>
<input type=submit  name=submit  value=submit>
</form>

(b)write code for searchst.php file:

<?php
$search = $_POST['search'];
// Read from file
$lines = file('example.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
}


?>

==============================================================================================================================================


Implode()  Function :

The implode function is used to "join elements of an array with a string".
The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice. 
The implode function in PHP is easily remembered as "array to string", which simply means that it takes an array and returns a string. It rejoins any array elements and returns the resulting string, which may be put in a variable.
Suppose you have an array like this $arr = Array ("A","E","I","O","U");

and you wish to combine it into a string, by putting the separator '-' between each element of the array.

How to do that?

$str = implode("-",$arr);

So your resulting string variable $str will be contain:
A-E-I-O-U

Syntax :

implode (separator , array)

Example1:

<html>
<
body bgcolor="pink">
<
h3>Implode Function</h3>
<?php
$arr=
array ('I','am','simple','boy!');
echo 
implode(" ",$arr);
?>
</
body>
</html>

Output :
I am simple boy!




Explode () Function :

The explode function is used to "Split a string by a specified string into pieces i.e. it breaks a string into an array".
The explode function in PHP allows us to break a string into smaller text with each break occurring at the same symbol. This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.
For example you have a string 

$str="A E I O U";

now you want to make each name as an element of an array and access it individually so what you do:

$arr = explode(",", $str);

means : we have made pieces of string $text based on separator ','
and put the resulting array in variable $arr

So I used print_r ($arr); and the results are the following:

Array(
[0] => A
[1] => E
[2] => I
[3] => O
[4] => U
)

which is equal to:

$arr = Array ("A","E","I","O","U");

Syntax:

explode (separator,string,limit)
 
 
 
Example1:

<html>
<
body bgcolor="pink">
<
h3>Explode Function</h3>
<?php
$str="I am simple boy!";
print_r(explode(
" ",$str));
?>
</body>
</html>

Output:

Array ( [0] => I [1] => am [2] => simple [3] => boy! )


Simple example for multiple selection using dropdown   with  implode function :

(1)first write code for  select.html file:

<form action=select.php  method=post>

<select name=city[]  multiple="multiple">
<option  value=mumbai>mumbai</option>
<option  value=delhi>delhi</option>
<option  value=goa>goa</option>
</select>
<input type=submit name=submit>
</form>

output:

(2)now  write code for select.php file:

<?php

$data=implode(',',$_POST['city']);

$con=mysql_connect('localhost','root','');

mysql_select_db("batch",$con);

$sql="insert into  test(city)values('$data')";

mysql_query($sql) or die(mysql_error());

?>



 Simple example for multiple selection using  Checkboxes  with  implode function :

(1)first write code for checkbox.html file:

<form   action=checkbox.php     method=post>
mumbai<input type=checkbox  name=city[]  value=mumbai>
Delhi<input type=checkbox   name=city[]   value=delhi>
city<input type=checkbox   name=city[]      value=city>
<input type=submit  name=submit   value=submit>
</form>

output:


(2) write  code for checkbox.php  file  :

<?php

$data=implode(',',$_POST['city']);

$con=mysql_connect('localhost','root','');

mysql_select_db("batch",$con);

$sql="insert into  test(city)values('$data')";

mysql_query($sql) or die(mysql_error());

?>




================================================================================================================================================
Definition   and   Usage   :

The   mysqli_real_escape_string()   function escapes
special characters in a string for use in an SQL statement.

Syntax :
mysqli_real_escape_string(connection,escapestring);

connection :   Required. Specifies the MySQL connection to use
escapestring:         
Required. The string to be escaped.
Characters  encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Example :

<?php

$con=mysql_connect("localhost","root","");

// Check connection
if (!$con) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$firstname = mysql_real_escape_string($con, $_POST['firstname']);
$lastname = mysql_real_escape_string($con, $_POST['lastname']);
$age = mysql_real_escape_string($con, $_POST['age']);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";

if (!mysqli_query($con,$sql)) {
  die( mysql_error());
}
echo "1 record added";


?>



Definition and  Usage  :
The  stripslashes()   function removes backslashes added by the addslashes()   function.

Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

Syntax :
stripslashes(string)

String :  Required. Specifies the string to check

Example   :

<!DOCTYPE html>
<html>
<body>

<?php

echo stripslashes("Who\'s Peter Griffin?");

?>

</body>
</html>

EXAMPLE:

<?php
$str = addcslashes("Hello World!","W");
echo($str);
?>

 OUTPUT:

Hello \World!




Definition and Usage
The stripslashes() function removes backslashes added by the addslashes() function.

Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

Syntax :
stripslashes(string)

Parameter    Description
string Required. Specifies the string to check


<!DOCTYPE html>
<html>
<body>

<?php
echo stripslashes("Who\'s Peter Griffin?");
?>

</body>
</html>



OUTPUT:

Hello \World!



Definition and Usage:

The addcslashes() function returns a string with backslashes in front of the specified characters.

Note: The addcslashes() function is case-sensitive.

Note: Be careful using addcslashes() on 0 (NULL), r (carriage return), n (newline), f (form feed), t (tab) and v (vertical tab). In PHP, \0, \r, \n, \t, \f and \v are predefined escape sequences.

Syntax :
addcslashes(string,characters)

string:        Required. Specifies the string to be escaped
characters:  Required. Specifies the characters or range of characters to be escaped




EXAMPLE:

<!DOCTYPE html>
<html>
<body>

<?php
$str = "Welcome to my humble Homepage!";
echo $str."<br>";
echo addcslashes($str,'A..Z')."<br>";
echo addcslashes($str,'a..z')."<br>";
echo addcslashes($str,'a..g');
?>

</body>
</html>

OUTPUT:
Welcome to my humble Homepage!
\Welcome to my humble \Homepage!
W\e\l\c\o\m\e \t\o \m\y \h\u\m\b\l\e H\o\m\e\p\a\g\e!
W\el\com\e to my hum\bl\e Hom\ep\a\g\e!






==============================================================================================================================================

how to generate Random numbers without rand() function?


<?php
   $num=range(1,20);
   shuffle($num);
   for ($i=0; $i<5; $i++) {    
      $result[$i]=$num[$i];  
   }  
   sort($result);  
   print_r($result);
?>

Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)
Parameters:
  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
The example below creates a constant with a case-sensitive name:
<?php

define("GREETING", "Welcome to vissicomp.com!");

echo GREETING;

?>

Output:
Welcome to vissicomp.com!



Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

1 comments:

PHP Training Mumbai, PHP MySQL Training Mumbai, PHP Course Mumbai, PHP Institute Mumbai

 

© 2013 PHP TRAINING IN MUMBAI BY OM SIR . All rights resevered. Designed by OM SIR

Back To Top