w1coding.comAll tutorials

PHP Strings

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

PHP String Functions

PHP provides various functions to manipulate strings. Some common ones are strlen(), strpos(), and str_replace().

Getting String Length

To get the length of a string, use the strlen() function:

      
        <?php
          $str = "Hello, World!";
          echo strlen($str); // Outputs 13
        ?>
      
    

Finding Substrings

To find the position of a substring in a string, use strpos():

      
        <?php
          $str = "Hello, World!";
          echo strpos($str, "World"); // Outputs 7
        ?>
      
    

Replacing Text

To replace a substring in a string, use str_replace():

      
        <?php
          $str = "Hello, World!";
          echo str_replace("World", "PHP", $str); // Outputs Hello, PHP!
        ?>
      
    

Activity

Try It Yourself!

Write a script that replaces a given word in a sentence with another word.

Quiz

Quick Quiz

  1. What function do you use to find the length of a string in PHP?
  2. How do you replace text in a string in PHP?

Answers: Use strlen() to get the length. Use str_replace() to replace text in a string.