PHP Strings
# 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 " ".
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.
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 returnsfalse.
6. String Replacement
Replacing text is incredibly common.-
str_replace(): Replaces some characters with some other characters in a string.
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*.
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 thesubstr() function.
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()returns0, NOT1.
-
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.combecomesjohn@gmail.com).
-
To sanitize spaces typed by accident at the beginning or end of a form input, always use
trim($string).
12. Exercises
-
1.
Create a variable
$email = " USER@gmail.com ". Usetrim()andstrtolower()to format it correctly and echo it.
-
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").14. Coding Challenges
Challenge 1: You have a string$filename = "document.pdf". Use str_replace() to change the extension from .pdf to .txt.
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: Doesstrreplace() 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!strreplace() 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 usingstrpos, replace text with str_replace, and format capitalization with strtolower and ucwords.