PHP String Functions: A Complete Reference
Strings are the backbone of most web applications, and PHP provides a rich set of functions to work with them. Whether you’re cleaning user input, generating dynamic content, or parsing data, mastering PHP’s string functions can dramatically improve code readability, performance, and security. This guide compiles every essential function, complete with syntax, examples, and best‑practice tips.
Table of Contents
- String Function Overview
- String Manipulation Functions
- Search & Replace Functions
- Formatting & Conversion Functions
- Encoding & Decoding Functions
- Regular Expression Helpers
- Performance & Security Tips
String Function Overview
PHP’s string handling can be divided into several logical groups:
- Basic length and case conversion
- Substring extraction
- Search, replace, and pattern matching
- Formatting, trimming, and padding
- Encoding/decoding (HTML, URL, Base64, etc.)
All functions are globally available; no special extensions are required in a standard PHP installation.
String Manipulation Functions
strlen()
Returns the length of a string in bytes.
$text = "Hello, World!";
echo strlen($text); // 13
substr()
Extracts a portion of a string. Supports negative offsets.
$url = "https://example.com/page";
echo substr($url, 8, -5); // "example.com"
str_split()
Splits a string into an array of characters (or chunks of a given length).
$chars = str_split("PHP", 1); // ['P','H','P']
str_repeat()
Repeats a string a specified number of times.
echo str_repeat("*", 5); // *****
trim(), ltrim(), rtrim()
Remove whitespace (or other characters) from the ends of a string.
$raw = " \tHello\n";
echo trim($raw); // "Hello"
Search & Replace Functions
strpos() & stripos()
Find the position of the first occurrence of a substring. stripos is case‑insensitive.
$pos = strpos("OpenAI ChatGPT", "Chat"); // 7
strrpos() & strripos()
Search from the end of the string.
$pos = strrpos("banana", "a"); // 5
substr_replace()
Replace a portion of a string with another string.
$result = substr_replace("Hello World", "PHP", 6, 5); // "Hello PHP"
str_replace() & str_ireplace()
Replace all occurrences of a search string. str_ireplace ignores case.
$text = str_replace("dog", "cat", "The dog barked."); // "The cat barked."
preg_replace()
Perform a regular‑expression based replacement.
$clean = preg_replace('/[^a-z0-9]/i', '', "User@123!"); // "User123"
Formatting & Conversion Functions
printf() & sprintf()
Format a string with placeholders.
number_format()
Format numbers with grouped thousands and custom decimal points.
echo number_format(1234567.89, 2, '.', ','); // 1,234,567.89
nl2br()
Convert newlines to HTML <br> tags.
echo nl2br("Line1\nLine2"); // "Line1
Line2"
htmlspecialchars() & htmlentities()
Escape characters for safe HTML output.
echo htmlspecialchars(""); // <script>alert('XSS');</script>
Encoding & Decoding Functions
urlencode() & urldecode()
Encode or decode URL query strings.
$q = urlencode("PHP string functions"); // "PHP+string+functions"
base64_encode() & base64_decode()
Encode binary data for safe transport.
$b = base64_encode("Hello"); // "SGVsbG8="
json_encode() & json_decode()
Convert between PHP values and JSON strings.
$json = json_encode(["name"=>"John","age"=>30]); // {"name":"John","age":30}
Regular Expression Helpers
preg_match() & preg_match_all()
Search a string for a pattern.
if (preg_match('/^PHP/', "PHP is great")) { echo "Match!"; }
preg_split()
Split a string by a regular expression.
$parts = preg_split('/\s+/', "One Two Three"); // ['One','Two','Three']
preg_grep()
Filter an array using a regular expression.
$emails = ["a@example.com","invalid","b@test.org"];
$valid = preg_grep('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $emails);
// $valid => ["a@example.com","b@test.org"]
Performance & Security Tips
- Prefer built‑in functions. Functions like
str_replaceare implemented in C and are faster than custom loops. - Use multibyte‑aware alternatives. When working with UTF‑8, replace
strlenwithmb_strlen,substrwithmb_substr, etc. - Escape user input. Always run
htmlspecialcharsbefore outputting data to HTML. - Cache repeated results. If you call a heavy regex repeatedly, store the result in a variable.
- Profile with Xdebug. Identify bottlenecks in string processing for large datasets.
Conclusion
PHP’s extensive string function library equips developers with everything needed to parse, transform, and secure textual data. By understanding the purpose and optimal usage of each function, you can write cleaner, faster, and more maintainable code. Keep this reference handy, experiment with the examples, and integrate the best‑practice tips to get the most out of PHP’s string handling capabilities.
1 thought on “PHP String Functions: A Complete Reference”