HOME HTML EDITOR C JAVA PHP

PHP Strings

A string is a sequence of characters, like "Hello world!". In PHP, strings can be written inside single quotes or double quotes.

1. String Length - strlen()

The strlen() function returns the total length of a string, including spaces and special characters.

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

2. Word Count - str_word_count()

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

<?php
  echo str_word_count("Hello world!"); // Outputs: 2
?>

3. Reverse a String - strrev()

The strrev() function is used to reverse a string.

<?php
  echo strrev("Hello world!"); // Outputs: !dlrow olleH
?>

4. Search Text - strpos()

The strpos() function searches for a specific text within a string. If found, it returns the character position. If not found, it returns FALSE.

<?php
  echo strpos("Hello world!", "world"); // Outputs: 6
?>

5. Replace Text - str_replace()

The str_replace() function replaces some characters with other characters in a string.

<?php
  echo str_replace("world", "Dolly", "Hello world!"); // Outputs: Hello Dolly!
?>
Important: String indexing always starts at 0. In "Hello", the 'H' is at index 0, and 'e' is at index 1.