Hey buddy, here are some handy-dandy PHP String functions for you.
heredoc is a way to declare strings using a special syntax, allowing multiline strings without needing to escape quotes.
echo <<<"FOOBAR"
Hello World!
FOOBAR;
nowdoc is kinda similar to heredoc but treats the enclosed string literally, ignoring variables and special characters.
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;
Get the length of a string
echo strlen($str1);
Convert a string to lowercase
echo strtolower($str1);
Convert a string to uppercase
echo strtoupper($str1);
Uppercase the first character of a string
echo ucfirst($str1);
Uppercase the first character of each word in a string
echo ucwords($str1);
Get a substring from a string starting at index 6
echo substr($str1, 6);
Get a substring from a string starting at index 6 with a length of 4
echo substr($str1, 6, 4);
Find the position of a substring in a string (case-sensitive)
echo strpos($str1, "Hello");
Find the position of a substring in a string (case-insensitive)
echo stripos($str1, "hello");
Convert an array into a string using implode
$arr1 = [1, "two"];
print_r(implode($arr1));
Convert a string into an array using explode
print_r(explode("@foo", $str1));
$str2 = "lol#oof#sheez";
print_r(explode("#", $str2));
Replace a substring in a string
$str2 = "welcome back!";
echo str_replace("back", "home", $str2);
Remove HTML tags from a string
$html_text_content = "<p>lol</p>";
echo strip_tags($html_text_content);
Escape special characters in a string
$name = "tom's world";
echo addslashes($name);
Remove slashes from a string
$str_with_slashes = "\yes \sir";
echo stripslashes($str_with_slashes);
Trim white spaces from the beginning and end of a string
$str_with_spaces = " no! ";
echo trim($str_with_spaces);
Shuffle characters in a string
$shuffle_me = "hello there!";
echo str_shuffle($shuffle_me);
Generate and display a 6-character OTP
$otp = "1726341237472364782346253";
echo substr(str_shuffle($otp), 0, 6);
Use md5 to a string (not recommended for password hashing)
$pwd = "password123";
echo md5($pwd);
echo password_hash($pwd, PASSWORD_DEFAULT);
Verify a password hash
$hash = '$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
Encode and decode strings to/from base64
$str3 = "test";
echo base64_encode($str3);
echo base64_decode("dGVzdA==j");
Do you have something more to add? Feel free to add them in the comment section to help other devs.
Top comments (0)