PHP – Strings Functions

Home / php-training-in-gurgaon / PHP – Strings Functions

String functions are the most important functions frequently used in PHP. String is the sequence of characters, like “Let’s learn String functions”. There is no installation required to use string function.

Example

<?php

$name = “Hirdesh Bhardwaj”;

print($name);

?>

String Concatenation Operator

To concatenate two string variables together, we use the dot (.) operator −

<?php

$txt1=”Hello Readers”;

$txt2=”8756″;

echo $txt1 . ” ” . $txt2;

?>

Using the strlen() function

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

<?php

$txt=”Webs Jyoti”;

echo strlen($txt);

?>

This will produce the following result – 10 (including space)

Using the strpos() function

The strpos() function is used to search for a text or character within a string. If the value is found then this will return the position of the first value. If no match is found, it will return FALSE.

Let’s see if we can find the string “PHP” in our string −

<?php

echo strpos(“Hello PHP”,”PHP”);

?>

This will produce the following result – 6

The explode() Function: Used to convert strings into an array variable.

Example:

$db = explode(‘;’,”host=localhost;db=hirdesh;uid=root “);

print_r($settings);

Output:

Array ( [0] => host=localhost [1] => db=hirdesh [2] => uid=root [3]

The substr() Function:

The substr() is used to return part of the string. It accepts three (3) basic parameters. The first one is the string to be shortened, the second parameter is the position of the starting point, and the third parameter is the number of characters to be returned.

 

The md5() Function: Used to calculate the md5 hash of a string value. This could be used where you want to convert your password from plain text to hash code to prevent the use of unauthorized users.

 

The trim() function : the Trim() is used to remove white spaces and predefined characters from a both the sides of a string.

Syntax

trim(string,charlist)

The str_replace() function: This can be used where you just want to swap out words or a set of characters in a string and replace them with something else.