Introduction
PHP’s extensive library of string functions and methods is indispensable for web development, ranging from simple data manipulation to complex pattern matching. This cheat sheet serves as a quick reference guide, highlighting how to effectively harness these capabilities in your PHP applications.
Basic String Functions
To get started, let’s explore some fundamental PHP string functions:
echo
– Outputs one or more strings.strlen()
– Returns the length of a string.str_replace()
– Replaces occurrences of a search string with a replacement string.strtolower()
andstrtoupper()
– Converts a string to lowercase and uppercase respectively.substr()
– Returns a portion of a string.
Example:
<?php
// Sample usage
$str = 'Hello, PHP!';
echo $str; // Output: Hello, PHP!
echo strlen($str); // Output: 12
echo str_replace('Hello', 'Hi', $str); // Output: Hi, PHP!
echo strtolower($str); // Output: hello, php!
echo strtoupper($str); // Output: HELLO, PHP!
echo substr($str, 7, 3); // Output: PHP
?>
Working with String Positions
Determining the position of substrings within a larger string is an essential operation:
strpos()
– Finds the position of the first occurrence of a substring in a string.strrpos()
– Finds the position of the last occurrence of a substring in a string.stripos()
– Case-insensitive version ofstrpos()
.
Example:
<?php
// Sample usage
$str = 'Learn PHP, Learn PHP!';
echo strpos($str, 'PHP'); // Output: 6
// Case-insensitive search
echo stripos($str, 'php'); // Output: 6
echo strrpos($str, 'PHP'); // Output: 13
?>
Comparing Strings
Comparison is another practical aspect of string manipulation:
strcmp()
– Compares two strings.strcasecmp()
– Case-insensitive string comparison.strnatcmp()
– Compares two strings using a ‘natural order’ algorithm.
Example:
<?php
// Sample usage
$str1 = 'string1';
$str2 = 'string2';
echo strcmp($str1, $str2); // Negative value, str1 is less than str2
echo strcasecmp($str1, strtoupper($str2)); // Output: 0, strings are equal case-insensitive
echo strnatcmp('img12.png', 'img2.png'); // Output: 1, '2' comes before '12' in natural order
?>
Advanced Pattern Matching with Regular Expressions
Regular expressions are powerful tools for complex string pattern matching and extraction:
preg_match()
– Performs a regular expression match.preg_replace()
– Performs a regular expression search and replace.preg_split()
– Splits a string by a regular expression pattern.
Example:
<?php
// Sample usage
$str = 'I have 2 apples and 3 oranges';
if (preg_match('/\d+/', $str, $matches)) {
echo 'Numbers found: ' . implode(', ', $matches);
}
// Replace words with numbers
echo preg_replace('/\d+/', 'many', $str);
// Split the string at each number
echo
preg_split('/\d+/', $str);
?>
Handling Special Characters
Special characters often need to be handled differently in strings. Here are functions to aid in that:
addslashes()
– Escapes a string with backslashes.stripslashes()
– Un-escapes a string.htmlentities()
– Converts characters to HTML entities.htmlspecialchars()
– Converts special characters to HTML entities.
Example:
<?php
// Sample usage
$str = "John's new car";
echo addslashes($str); // Output: John\'s new car
echo stripslashes(addslashes($str)); // Output: John's new car
echo htmlentities($str); // Output: "John's new car"
echo htmlspecialchars($str); // Output: "John's new car"
?>
String Encoding and Decoding
Encoding and decoding string data is vital for web security and interoperability:
urlencode()
– URL-encodes a string.urldecode()
– Decodes URL-encoded string.base64_encode()
– Encodes data with MIME base64.base64_decode()
– Decodes data encoded with MIME base64.
Example:
<?php
// Sample usage
$str = '[email protected]';
echo urlencode($str); // Output: user%40example.com
echo urldecode($str); // Output: [email protected]
echo base64_encode($str); // Output: dXNlckBleGFtcGxlLmNvbQ==
echo base64_decode('dXNlckBleGFtcGxlLmNvbQ=='); // Output: [email protected]
?>
Formatting Strings
PHP offers functions to format strings:
sprintf()
– Returns a formatted string.printf()
– Output a formatted string.
Example:
<?php
// Sample usage
$number = 9;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $number, $location); // Output: There are 9 monkeys in the tree
printf($format, $number, $location); // Outputs directly: There are 9 monkeys in the tree
?>
Conclusion
PHP’s string functions provide a comprehensive toolkit for developers to perform virtually any operation on string data. Whether you are new to PHP or an experienced developer, refer back to this cheat sheet to streamline your coding workflow when working with strings.