String functions in php

implode()

The implode function used to concatenate the array elements as a string with a separator.

Syntax: implode(separator, array)

<?php
$var = array("Apple", "Boy", "Cat", "Dog");
$alpha= implode(",",$var);
echo $alpha;
?>

Output:

Apple,Boy,Cat,Dog

explode()

This function is vise versa of the implode function. In this function the string is split in to array elements. It breaks a text in to smaller text.

Syntax: explode(separator, string, limit)

<?php
$str = "I have Car, I have Bike, I go to School";
$exp = explode(",",$str);
print_r($exp);	
?>

Output:

Array (
    [0] => I have Car
   [1] => I have Bike
   [2] => I go to School
)

trim()

The trim function is used to remove whitespace and predefined characters from both side of a string.

syntax: trim(string, charlist)

ltrim(): This function is used to trim the string from left side.

rtrim(): This function is used to trim the string from right side.

<?php
$str = "That is a Pen";
echo "<br>";
echo trim($str, "Then");
?>

Output:

at is a P

str_replace()

The str_replace() function is used to replace any character with some other character in a string.

syntax: str_replace(find,replace,string,count)

<?php
echo str_replace("John","Peter","John is good.");
?>

Output:

Peter is good.

strtolower()

The strtolower() function is used to convert all the characters in lowercase of a string.

syntax: strtolower(string)

<?php
echo strtolower("JOHN IS GOOD.");
?>

Output:

john is good.

strtoupper()

The strtoupper() function is used to convert all the characters in uppercase of a string.

syntax: strtoupper(string)

<?php
echo strtoupper("John is good.");
?>

Output:

JOHN IS GOOD.

strlen()

The strlen() function is used to count the length of a string.

syntax: strlen(string)

<?php
echo strlen("John is good.");
?>

Output:

15

substr()

The substr() function is used for print the specific part of a string.

syntax: substr(string,start,length)

<?php
echo substr("John is good.", 3);
?>

Output:

n is good.

Leave a Reply