strings

PHP String Functions

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.