Friday, January 13

PHP String Functions with Example

<?php
//Get The Length of a String :Example
echo strlen("Welcome WEB!"); // outputs 10

//Count The Number of Words in a String :Example
echo str_word_count("Welcome WEB!"); // outputs 2

//Reverse a String :Example
echo strrev("Hello world!1"); // outputs 1!dlrow olleH

//Search For a Specific Text Within a String :Example
 echo strpos("Hello world!", "world"); // outputs 6

//Replace Text Within a String :Example
echo str_replace("world", "King", "Hello world!"); // outputs Hello King!


//PHP Strlen() Function :Example

$name="king";
if ( strlen( $name ) != 5 ) 
{
    echo "Correct input.";
}
else
{
    echo "incorrect input";
}

//PHP chr() FUNCTION :Example
echo chr(35); //#

//PHP strcmp()FUNCTION :Example
<?php echo strcmp("Hello world!","Hello world!"); ?> //Returns 0

//PHP explode()FUNCTION :Example

 $str = "Hello world. It's a beautiful day.";
 print_r (explode(" ",$str));
/* Output :
Array
 (
 [0] => Hello
 [1] => world.
 [2] => It's
 [3] => a
 [4] => beautiful
 [5] => day.
 )
*/

//PHP implode()FUNCTION :Example

$arr = array('Hello','World!','Beautiful','Day!');
 echo implode(" ",$arr);
/*
Output:
Hello World! Beautiful Day!
*/

//PHP str_replace()FUNCTION :Example

 $phrase  = "You should eat fruits, vegetables, and fiber every day.";
 $healthy = array("fruits", "vegetables", "fiber");
 $yummy   = array("pizza", "beer", "ice cream");
 $newphrase = str_replace($healthy, $yummy, $phrase);

/*
Output :
You should eat pizza, beer, and ice cream every day
*/

//PHP substr()FUNCTION :Example

 echo substr("Hello world",6);  //Returns world
 echo substr("Hello world",6,4); // Returns worl
 echo substr("Hello world", -1); // Returns  d
 echo substr("Hello world", -3, -1); // Returns rl

?>

No comments:

Post a Comment

10 Best Chatting Apps In India

  The modern world is all about Internet. There was a time when people use to pay high telephone bills to stay in touch with their friends a...