CITW 185 Web Development PHP & MySQL
Working with Strings in PHP
1. What Are Strings?
- Strings are sequences of characters, such as letters, numbers, and symbols, used to represent text.
- In PHP, strings can be created using either single quotes (
'
) or double quotes ("
).
2. Why Are Strings Important?
- Strings are fundamental for any application that deals with user input, messages, or any form of textual data.
- They enable dynamic content, such as displaying user-specific information or generating formatted reports.
3. Key Features
- String Concatenation: Combine multiple strings using the
.
operator.
- String Interpolation: Embed variables directly within double-quoted strings.
- String Functions: PHP provides a wide range of built-in functions for string manipulation, such as:
strlen()
- Returns the length of a string.
strpos()
- Finds the position of the first occurrence of a substring.
substr()
- Extracts a portion of a string.
str_replace()
- Replaces all occurrences of a substring with another string.
trim()
- Removes whitespace from both ends of a string.
4. Best Practices
- Use double quotes when variables need to be embedded directly in the string.
- Use single quotes for plain text to improve performance.
- Always sanitize user inputs to avoid security risks like SQL injection or XSS.
Assignments
-
Strings
-
Strings Revisited
-
String Replace
-
Your creative assignment is to demonstrate your command of strings. I suggest you use a form to
gather values and then preform a series of string operations to present your understanding of
string manipulations.