PHP Strings Functions

PHP String functions provide various ways to access and manipulate strings. The String functions are part of the PHP core. Some commonly used functions are as follows :

strlen()
str_word_count()
strrev()
strpos()
str_replace()
strtolower()
strtoupper()


1. strlen() :

The strlen() function returns the length of a string.

Example :
<?php

  $str = "Hello world This is String.";
  echo strlen($str);

?>
Output :

27

2. str_word_count()

The str_word_count() function counts the number of words in a string.

Example :
<?php

  $str = "Hello world This is String.";
  echo str_word_count($str);

?>
Output :

5

3. strrev() :

The strrev() function reverses a string.

Example :
<?php

  $str = "Hello world This is String.";
  echo strrev($str);

?>
Output :

.gnirtS si sihT dlrow olleH

4. strpos() :

The strpos() function is used to search a specific text within a string. If a match is found, then the function retuens the character position of the first match, otherwise it returns false. The syntax is as follows :
 strpos(string, word_to_search);
Where string is a string variable or string and word_to_search is a word you want to search.

Example :
<?php

  $str = "Hello world This is String.";
  echo strpos($str, "world");

?>
Output :

6

5. str_replace()

The str_replace() function is used to replaces some characters with some other characters in a string. The syntax is as follows :
 str_replace(word_to_replace, word_to_replace_with, string);
Where word_to_replace is word you want to replace (or remove) and word_to_replace_with is the word you want to put on the replaced word place.

Example :
<?php

  $str = "Hello world This is String.";
  echo str_replace("world", "people", $str);
  
?>
Output :

Hello people This is String.

6. strtolower() :

The strtolower() function is used to convert the string into lower case string, it returns the lowercase string.

Example :
<?php

  $str = "Hello World This is String.";
  echo strtolower($str);

?>
Output :

hello world this is string.

7. strtoupper()

The strtoupper() function is used to convert the string into upper case string, it returns the uppercase string.

Example :
<?php

  $str = "Hello World This is String.";
  echo strtoupper($str);
  
?>
Output :

HELLO WORLD THIS IS STRING.


Next Topic :