PHP String Functions

PHP provides many built-in functions for manipulating strings.In this chapter we will look at some commonly used functions to manipulate strings.

> Using the strlen() function

This function Returns the length of a string.

<?php
    echo strlen("Hello world!"); // outputs 12
?>

> Using the trim() function

This function use to removes whitespace or other characters from both sides of a string.

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

> Using the str_word_count() function

This function use to counts the number of words in a string.

<?php
    $my_str = 'This is PHP tutorial.';
    echo str_word_count($my_str);
?>

> Using the strpos() function

This function use to search for a string or character within a string.

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

> Using the str_replace() function

This function use to replaces all occurrences of the search text within the target string.

<?php
    $my_str = 'This is PHP tutorial.';
    echo str_replace("tutorial","website",$my_str);
?>

> Using the strrev() function

This function use to reverses a string.

<?php
    $my_str = 'This is PHP tutorial.';
    echo strrev($my_str);
?>

> Using the substr() function

This function use to returns a specif part of string.

<?php
    echo substr("Hello world",-5);
?>

> Using the strtoupper() function

This function use to convert all characters to uppercase.

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

> Using the lowercase() function

This function use to convert all characters to lowercase.

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