PHP String Functions

PHP provides several built-in functions to manipulate strings easily. These functions help with **finding lengths, replacing text, changing case, extracting substrings**, and more.

๐Ÿ”น Commonly Used PHP String Functions

Here are some essential PHP string functions:

  • strlen() – Get the length of a string.
  • strtolower() / strtoupper() – Convert string case.
  • trim() – Remove whitespace from both ends.
  • substr() – Extract part of a string.
  • str_replace() – Replace text in a string.
  • strpos() – Find the position of a substring.

๐Ÿ“ Example 1: Get String Length

The strlen() function returns the number of characters in a string.

<?php
$text = "Hello, World!";
echo "Length: " . strlen($text);
?>

Try It Now


๐Ÿ“ Example 2: Convert String to Lowercase & Uppercase

Use strtolower() and strtoupper() to change case.

<?php
$text = "Hello, World!";
echo "Lowercase: " . strtolower($text) . "<br>";
echo "Uppercase: " . strtoupper($text);
?>

Try It Now


๐Ÿ“ Example 3: Trim Whitespace

The trim() function removes extra spaces from the beginning and end of a string.

<?php
$text = "   Hello, World!   ";
echo "Without trim: '$text' <br>";
echo "With trim: '" . trim($text) . "'";
?>

Try It Now


๐Ÿ“ Example 4: Extract a Substring

The substr() function extracts part of a string.

<?php
$text = "Hello, World!";
echo "Extracted: " . substr($text, 7, 5);
?>

Try It Now

Explanation: Extracts 5 characters starting from index 7, outputting World.


๐Ÿ“ Example 5: Replace Text in a String

The str_replace() function replaces words in a string.

<?php
$text = "I love PHP!";
$new_text = str_replace("PHP", "coding", $text);
echo $new_text;
?>

Try It Now

Explanation: Replaces PHP with coding, outputting I love coding!.


๐Ÿ“ Example 6: Find Position of a Word

The strpos() function finds the position of the first occurrence of a substring.

<?php
$text = "Hello, World!";
$position = strpos($text, "World");
echo "Position of 'World': " . $position;
?>

Try It Now

Explanation: Finds World at index 7.


๐Ÿ”น Key Takeaways

  • Use strlen() to find the length of a string.
  • Use strtolower() and strtoupper() to change case.
  • Use trim() to remove unnecessary whitespace.
  • Use substr() to extract parts of a string.
  • Use str_replace() to replace text in a string.
  • Use strpos() to locate substrings.

๐Ÿ“ Practice Time!

Try modifying these examples and experiment with PHP string functions to improve your understanding! ๐Ÿš€