Saturday, 15 December 2012

PHP String Functions

String concatenation operator in php

We know very well that concatenation means nothing but join together two strings. In php concatenation operator (.)  is used to join two string values together.

<?php
$txt1="Hello World!";
$txt2="Welcome!";
echo $txt1 . " " . $txt2;
?>

the output of the above programe look like this:
Hello World! Welcome!

Length of a string

The function 'strlen' is used to return the length of the string that is passed as an argument. Syntax of the strlen function is given below

syntax:
strlen(stringname);

Example:
$string="sample";
strlen($string);

Output :
6

Splitting a string into an array

The function 'explode' is used to split a string into an array using a separator. It takes the separator and the string as its argument. Syntax of the explode function is given below

Syntax:
explode(separator,stringname);

Example:
$string="11-02-2005"
explode("-",$string);

Output :
11 in array[0] , 02 in array[1] , 2005 in array[2]

Joining the array elements into a single string

The function 'join' is used to join various array elements into a single string. Alternatively 'implode' can also be used to join array elements into a string. Syntax of the join and implode function is given below

Syntax:
join(separator,arrayname);
(or)
implode(separator,arrayname);

Example:
$arraystring=array("s","sample","java");
implode("/",$arraystring);

Output :
s/sample/java

Repeating a string 'n' times

The function 'str_repeat' is used to repeat a given string 'n' times. The function takes the string and the number of times to be repeated as its argument.yntax of the str_repeat function is given below
Syntax of the str_repeat function:
str_repeat($string,integervalue); 

Example:
str_repeat("welcome! ",2); 

Output :
welcome! welcome! 

Remove HTML tags from the string

The function 'strip_tags' is used to remove the HTML tags present in a string by taking the string as its argument.

Syntax of the strip_tags function is given below
string strip_tags ( string $str [, string $allowable_tags ] )

Example:
<?php
$text '<p>Web.</p><!-- Comment --> <a href="#">Other text</a>';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text'<p><a>');
?>

Output:
Web. Other text
<p>web.</p> <a href="#">Other text</a>

0 comments:

Post a Comment