PHP String Functions: A Complete Guide
Robin Dev
Posted on January 5, 2023
Are you working with strings in PHP and looking for ways to manipulate them? PHP provides a variety of built-in functions that can help you do just that. In this post, we’ll go over some of the most common string functions in PHP and how they can be used.
-
strlen
: This function returns the length of a string. For example:
$str = "Hello world";
echo strlen($str); // Outputs "11"
-
strtolower
: This function converts a string to lowercase. For example:
$str = "HELLO WORLD";
echo strtolower($str); // Outputs "hello world"
-
strtoupper
: This function converts a string to uppercase. For example:
$str = "hello world";
echo strtoupper($str); // Outputs "HELLO WORLD"
-
substr
: This function returns a portion of a string. It takes two arguments: the string and the start and end indices (inclusive). For example:
$str = "Hello world";
echo substr($str, 0, 5); // Outputs "Hello"
str_replace
: This function replaces all occurrences of a search string with a replacement string. It takes three arguments: the search string, the replacement string, and the original string. For example:
$str = "Hello world";
echo str_replace("world", "PHP", $str); // Outputs "Hello PHP"
-
strpos
: This function returns the position of the first occurrence of a search string. It takes two arguments: the search string and the original string. For example:
$str = "Hello world";
echo strpos($str, "world"); // Outputs "6"
-
strtr
: This function translates certain characters in a string. It takes two arguments: the original string and an array of translations. For example:
$str = "Hello world";
echo strtr($str, array("world" => "PHP")); // Outputs "Hello PHP"
-
htmlspecialchars
: This function converts special characters to HTML entities. This is useful for displaying text on a web page, as the special characters will be displayed as-is instead of being interpreted as HTML. For example:
$str = "<p>This is a paragraph</p>";
echo htmlspecialchars($str); // Outputs "<p>This is a paragraph</p>"
-
nl2br
: This function inserts HTML line breaks before all newlines in a string. This is useful for displaying text with line breaks on a web page. For example:
$str = "This is a paragraph\nThis is another paragraph";
echo nl2br($str); // Outputs "This is a paragraph<br>This is another paragraph"
-
trim
: This function removes whitespace from the beginning and end of a string. For example:
$str = " Hello world ";
echo trim($str);
These are the some basic string functions in PHP, I hope it will help. Thanks Larachamp
The post PHP String Functions: A Complete Guide appeared first on Larachamp.
💖 💪 🙅 🚩
Robin Dev
Posted on January 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.