PHP String Functions List


Here’s a list of common string functions in PHP:

  1. strlen() - Returns the length of a string.

    strlen("Hello World"); // 11
  2. str_word_count() - Counts the number of words in a string.

    str_word_count("Hello World"); // 2
  3. strpos() - Finds the position of the first occurrence of a substring.

    strpos("Hello World", "World"); // 6
  4. str_replace() - Replaces some characters in a string.

    str_replace("World", "PHP", "Hello World"); // Hello PHP
  5. substr() - Returns part of a string.

    substr("Hello World", 6); // World
  6. trim() - Removes whitespace or other characters from the beginning and end of a string.

    trim(" Hello World "); // "Hello World"
  7. strtolower() - Converts a string to lowercase.

    strtolower("HELLO WORLD"); // hello world
  8. strtoupper() - Converts a string to uppercase.

    strtoupper("hello world"); // HELLO WORLD
  9. ucfirst() - Capitalizes the first letter of a string.

    ucfirst("hello world"); // Hello world
  10. lcfirst() - Converts the first letter of a string to lowercase.

    lcfirst("Hello World"); // hello World
  11. ucwords() - Capitalizes the first letter of each word in a string.

    ucwords("hello world"); // Hello World
  12. md5() - Calculates the MD5 hash of a string.

    md5("hello"); // 5d41402abc4b2a76b9719d911017c592
  13. sha1() - Calculates the SHA-1 hash of a string.

    sha1("hello"); // aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
  14. addslashes() - Escapes a string with backslashes.

    addslashes("O'Reilly"); // O\'Reilly
  15. htmlspecialchars() - Converts special characters to HTML entities.

    htmlspecialchars("<a href='test'>Test</a>"); // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
  16. str_repeat() - Repeats a string a specified number of times.

    str_repeat("Hello", 3); // HelloHelloHello
  17. explode() - Splits a string by a string and returns an array.

    explode(" ", "Hello World"); // ["Hello", "World"]
  18. implode() (alias of join()) - Joins array elements with a string.

    implode("-", ["Hello", "World"]); // Hello-World
  19. strrev() - Reverses a string.

    strrev("Hello"); // olleH
  20. similar_text() - Calculates the similarity between two strings.

    similar_text("Hello", "Hell"); // 80 (percent similarity)
  21. number_format() - Formats a number with grouped thousands.

    number_format(1000000); // 1,000,000
  22. ord() - Returns the ASCII value of the first character of a string.

    ord("A"); // 65
  23. chr() - Returns a character from a specified ASCII value.

    chr(65); // A
  24. parse_str() - Parses a query string into variables.

    parse_str("name=John&age=25", $output); // $output = ["name" => "John", "age" => "25"]
  25. sprintf() - Returns a formatted string.

    sprintf("There are %d apples", 5); // There are 5 apples

These functions are widely used for string manipulation in PHP. Let me know if you need examples or explanations for any specific ones!