PHP provides a rich set of functions to work with strings. Let's dive into different aspects of PHP strings:
Defining Strings: Strings in PHP can be defined using single quotes (') or double quotes (").
$single_quoted = 'Hello, world!';
$double_quoted = "Hello, world!";
The difference is that double-quoted strings can evaluate variables inside them, while single-quoted strings cannot.
$name = "John";
echo 'Hello, $name'; // Outputs: Hello, $name
echo "Hello, $name"; // Outputs: Hello, John
Concatenation: You can concatenate strings using the . operator.
$first = "Hello, ";
$second = "world!";
echo $first . $second; // Outputs: Hello, world!
String Length: Use strlen() to get the length of a string
$str = "Hello";
echo strlen($str); // Outputs: 5
String Functions:
strpos(): Find the position of the first occurrence of a substring in a string.
echo strpos("Hello world!", "world"); // Outputs: 6
str_replace(): Replace all occurrences of a search string with a replacement string.
echo str_replace("world", "Dolly", "Hello world!"); // Outputs: Hello Dolly!
strtolower() and strtoupper(): Convert a string to lowercase or uppercase.
echo strtolower("HELLO"); // Outputs: hello
echo strtoupper("hello"); // Outputs: HELLO
substr(): Extract a portion of a string.
echo substr("Hello world!", 0, 5); // Outputs: Hello
trim(): Strip whitespace (or other characters) from the beginning and end of a string.
echo trim(" Hello world! "); // Outputs: Hello world!
Escape Sequences: In double-quoted strings, certain sequences of characters have special meanings:
Example:
echo "Hello\nWorld!"; // Outputs:
// Hello
// World!
Heredoc and Nowdoc Syntax: These are methods to define large, multiline strings.
Heredoc:
$str = <<<EOD
This is a
multiline string.
EOD;
echo $str;
Nowdoc (similar to single-quoted strings):
$str = <<<'EOD'
This is a
multiline string without parsing.
EOD;
echo $str;
String comparison:
Strings can be compared using the equality (==) and identity (===) operators, as well as functions like strcmp().
$a = "Hello";
$b = "hello";
if ($a == $b) {
echo "Equal";
} else {
echo "Not Equal"; // Outputs: Not Equal because string comparison is case-sensitive
}
echo strcmp($a, $b); // Returns a negative, zero, or positive number.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here