Strings are one of the most commonly used data types in PHP. Whether you're processing user input, formatting text, or working with data, knowing the right string functions can save time and improve code quality.
In this guide, you'll learn the most essential PHP string functions every developer should know, along with practical examples.
1. strlen()
Returns the length of a string.
$text = "Hello";
echo strlen($text); // 5
2. str_replace()
Replaces all occurrences of a string.
$text = "Hello World";
echo str_replace("World", "PHP", $text); // Hello PHP
3. strpos()
Finds the position of the first occurrence of a substring.
$text = "Hello PHP";
echo strpos($text, "PHP"); // 6
4. substr()
Returns part of a string.
$text = "Hello World";
echo substr($text, 0, 5); // Hello
5. strtolower()
Converts a string to lowercase.
echo strtolower("HELLO"); // hello
6. strtoupper()
Converts a string to uppercase.
echo strtoupper("hello"); // HELLO
7. trim()
Removes whitespace from the beginning and end of a string.
$text = " hello ";
echo trim($text); // "hello"
8. explode()
Splits a string into an array.
$text = "apple,banana,orange";
print_r(explode(",", $text));
9. implode()
Joins array elements into a string.
$arr = ["apple", "banana"];
echo implode(", ", $arr); // apple, banana
10. ucfirst()
Capitalizes the first character of a string.
echo ucfirst("hello"); // Hello
11. ucwords()
Capitalizes the first letter of each word.
echo ucwords("hello world"); // Hello World
12. htmlspecialchars()
Converts special characters to HTML entities (important for security).
echo htmlspecialchars("<script>");
// <script>
13. strip_tags()
Removes HTML and PHP tags from a string.
echo strip_tags("<b>Hello</b>"); // Hello
Real-World Example
<?php
$name = " john doe ";
$name = trim($name);
$name = ucwords($name);
echo $name; // John Doe
Best Practices
- Always sanitize user input
- Use
htmlspecialchars()to prevent XSS - Choose the right function instead of writing custom logic
Common Mistakes
- Confusing
strpos()return value with false - Not trimming input data
- Using string functions on non-string variables
FAQ
What is the most used PHP string function?
Functions like strlen(), str_replace(), and strpos() are widely used.
How do I make a string uppercase?
Use strtoupper().
How do I split a string in PHP?
Use explode().
How do I secure user input?
Use htmlspecialchars() to escape output.
Conclusion
PHP string functions are powerful tools that help you manipulate and process text efficiently. Mastering them will significantly improve your development workflow.