Skip to main content
PHP for Beginners
CHAPTER 11 Beginner

PHP Strings

Updated: May 12, 2026
15 min read

# Chapter 11: PHP Strings

1. Introduction

Welcome to Chapter 11! Text is everywhere on the web—usernames, blog posts, product descriptions. In PHP, text is represented as a String. You already know how to create strings and echo them out, but what if you need to manipulate them? What if a user enters their name as "jOhN DoE" and you want to neatly format it as "John Doe"? Or what if you want to censor a bad word in a comment? PHP provides a massive library of built-in string functions to do exactly that.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Review string concatenation and parsing.
  • Count the length and words in a string.
  • Find specific text within a string.
  • Replace portions of a string.
  • Format text capitalization automatically.

3. String Concatenation and Parsing (Review)

You can join strings using the dot . operator, or you can parse variables directly inside double quotes " ".
php
123456
<?php
$food = "Pizza";
echo "I love " . $food . "!"; // Concatenation
echo "<br>";
echo "I love $food!";         // Parsing (Double quotes only)
?>

4. Basic String Functions

Let's look at functions that give us information about our strings.
  • strlen(): Returns the length (number of characters) of a string.
  • strwordcount(): Returns the number of words in a string.
php
123456
<?php
$sentence = "Backend development is awesome.";
echo strlen($sentence); // Outputs: 31 (including spaces and punctuation)
echo "<br>";
echo str_word_count($sentence); // Outputs: 4
?>

5. String Searching

Sometimes you need to know if a specific word exists inside a string, and where it is located.
  • strpos(): Searches for a specific text within a string. It returns the character position of the *first* match. If no match is found, it returns false.
php
12345
<?php
// Note: Positions start at 0, just like arrays!
$text = "Welcome to the PHP course!";
echo strpos($text, "PHP"); // Outputs: 15
?>

6. String Replacement

Replacing text is incredibly common.
  • str_replace(): Replaces some characters with some other characters in a string.
php
123456
<?php
$greeting = "Hello World!";
// str_replace(search_for, replace_with, original_string)
$new_greeting = str_replace("World", "Universe", $greeting);
echo $new_greeting; // Outputs: Hello Universe!
?>

7. String Capitalization Formatting

When dealing with user input, data is often messy. You can clean it up instantly.
  • strtolower(): Converts a string to all lowercase.
  • strtoupper(): Converts a string to all uppercase.
  • ucwords(): Capitalizes the first letter of *every word*.
php
12345
<?php
$messy_name = "jAcOb sMiTh";
$clean_name = ucwords(strtolower($messy_name));
echo $clean_name; // Outputs: Jacob Smith
?>

8. Real-World Examples

Imagine you are building a blog, and you only want to show an excerpt (the first 20 characters) of the article on the homepage. You can use the substr() function.
php
12345678
<?php
$article = "PHP powers the vast majority of websites on the modern internet.";
// substr(string, start_position, length)
$excerpt = substr($article, 0, 20);

echo $excerpt . "... Read More"; 
// Outputs: PHP powers the vast ... Read More
?>

9. Output Explanations

In the capitalization example: ucwords(strtolower($messyname)). First, PHP runs the innermost function: strtolower("jAcOb sMiTh"), which turns it into "jacob smith". Then, it passes that result to the outer function: ucwords("jacob smith"), which capitalizes the first letters, resulting in the final string "Jacob Smith".

10. Common Mistakes

  • Confusing Character Position: Remember that strpos() is 0-indexed. If a string starts with the word you are looking for, strpos() returns 0, NOT 1.
  • Modifying the Original String? None of these string functions modify the original variable! They return a brand new string. You must save the result if you want to keep it ($text = strtoupper($text);).

11. Best Practices

  • When saving user emails or usernames to a database, always use strtolower() first so they are consistent (e.g. John@gmail.com becomes john@gmail.com).
  • To sanitize spaces typed by accident at the beginning or end of a form input, always use trim($string).

12. Exercises

  1. 1. Create a variable $email = " USER@gmail.com ". Use trim() and strtolower() to format it correctly and echo it.
  1. 2. Use strreplace() to change "I love cats" to "I love dogs".

13. Mini Project: Username Formatter

Task: Simulate a user registering an account. Take a messy username, clean the spaces, force it to lowercase, and check if it contains an invalid word (like "admin").
php
123456789101112131415161718192021222324252627282930
<?php
$raw_input = "   SuPer_AdMin_99   ";

// 1. Remove accidental spaces
$trimmed = trim($raw_input);

// 2. Convert to lowercase
$username = strtolower($trimmed);

// 3. Check for restricted words
$is_valid = true;
if (strpos($username, "admin") !== false) {
    $is_valid = false;
}
?>

<!DOCTYPE html>
<html>
<body>
    <h2>Username Registration</h2>
    <p>Raw Input: "<?php echo $raw_input; ?>"</p>
    <p>Formatted Username: "<?php echo $username; ?>"</p>
    
    <?php if ($is_valid): ?>
        <p style="color: green;">Username is valid and available!</p>
    <?php else: ?>
        <p style="color: red;">Error: Username cannot contain the word &#039;admin'.</p>
    <?php endif; ?>
</body>
</html>

14. Coding Challenges

Challenge 1: You have a string $filename = "document.pdf". Use str_replace() to change the extension from .pdf to .txt.
php
123456
<?php
// Solution
$filename = "document.pdf";
$new_filename = str_replace(".pdf", ".txt", $filename);
echo $new_filename;
?>

15. MCQs with Answers

1. Which function returns the length of a string? A) strlength() B) length() C) strlen() D) count() *Answer: C*

2. Why do we use !== false when checking the result of strpos()? A) Because false means error. B) Because if the word is at the very beginning of the string, it returns 0. In PHP 0 is loosely equal to false. Using !== ensures we check strictly for a boolean false. C) Because strpos always returns a string. D) We don't need to use it. *Answer: B*

3. What does trim() do? A) Cuts a string in half. B) Removes whitespace from both sides of a string. C) Capitalizes the string. D) Deletes the string. *Answer: B*

16. Interview Questions

Q: Does str
replace() alter the original string variable? *A:* No. String functions in PHP return a new string containing the modifications. If you want the original variable to change, you must reassign it: $x = strreplace("a", "b", $x);.

Q: Explain how to check if a substring exists within a string. *A:* You use the strpos($string, $substring) function. You must explicitly check if the result is !== false. If you just check if(strpos(...)), it will fail if the substring is found at the 0th index because 0 evaluates to false in a loose comparison.

17. FAQs

Q: Can I replace multiple different words at the same time? *A:* Yes! str
replace() can accept arrays. You can provide an array of search words and an array of replacement words to do multiple replacements in one line.

18. Summary

You are now a text manipulation master. You learned how to find the length of a string, search for specific words within it using strpos, replace text with str_replace, and format capitalization with strtolower and ucwords.

19. Next Chapter Recommendation

We touched on capturing basic input earlier. Now it's time to build a fully functional contact form. In Chapter 12: PHP Forms Handling, we will process inputs, validate data, and make sure it is safe!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·