PHP string functions


Answers ( 1 )


    Here's an overview of some commonly used PHP string functions along with code examples:

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

      echo strlen("Hello World"); // Outputs: 11
    2. str_replace(): Replaces all occurrences of a search string with a replacement string.

      echo str_replace("world", "user", "Hello world!"); // Outputs: Hello user!
    3. substr(): Returns a part of a string.

      echo substr("Hello World", 6); // Outputs: World
    4. strpos(): Finds the position of the first occurrence of a substring in a string.

      echo strpos("Hello world!", "world"); // Outputs: 6
    5. strtolower() and strtoupper(): Converts a string to lowercase or uppercase.

      echo strtolower("Hello WORLD!"); // Outputs: hello world!
      echo strtoupper("Hello world!"); // Outputs: HELLO WORLD!
    6. trim(): Removes whitespace or other predefined characters from both sides of a string.

      echo trim(" Hello World "); // Outputs: Hello World
    7. str_split(): Converts a string into an array.

      print_r(str_split("Hello", 2)); // Outputs: Array ( [0] => He [1] => ll [2] => o )
    8. strcmp(): Compares two strings.

      echo strcmp("Hello", "Hello"); // Outputs: 0
    9. sprintf(): Writes a formatted string to a variable.

      $num = 5;
      $location = 'tree';
      $format = 'There are %d monkeys in the %s';
      echo sprintf($format, $num, $location); // Outputs: There are 5 monkeys in the tree
    10. strrev(): Reverses a string.

      echo strrev("Hello world!"); // Outputs: !dlrow olleH

    These are just a few examples of the many string functions available in PHP. Each function has its specific use case, and understanding these functions is crucial for effective string manipulation in PHP programming.

Leave an answer