Strings in PHP
In this tutorial, we will learn about strings in PHP. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
What is a String
A string in PHP is a sequence of characters. Strings in PHP can be created using single quotes, double quotes, or the heredoc
and nowdoc
syntaxes. Strings are used for storing and handling text data.
Creating Strings
Strings can be created in PHP using single or double quotes:
$str = "Hello, world!";
Strings can also be created using heredoc
syntax:
$str2 = <<
Example 1: Initializing Strings
- Create a string variable and initialize it with a value.
- Print the string variable using
echo
.
PHP Program
<?php
$str = "Hello, world!";
echo $str;
?>
Output
Hello, world!
Example 2: Accessing Characters in a String
- Create a string variable and initialize it with a value.
- Access and print individual characters using array indexing.
PHP Program
<?php
$str = "Hello";
echo $str[0] . "\n"; // Accessing using array indexing
echo $str[1] . "\n";
?>
Output
H e
Example 3: Modifying Strings
- Create a string variable and initialize it with a value.
- Strings in PHP are mutable, so you can modify individual characters directly using array indexing or append new characters.
- Print the modified string.
PHP Program
<?php
$str = "Hello";
$str[0] = 'J'; // Modifying individual character
$str .= " World!"; // Appending new characters
echo $str;
?>
Output
Jello World!
Example 4: String Concatenation
- Create two string variables and initialize them with values.
- Concatenate the strings using the
.
operator. - Print the concatenated string.
PHP Program
<?php
$str1 = "Hello";
$str2 = " World!";
$str3 = $str1 . $str2; // Concatenating strings
echo $str3;
?>
Output
Hello World!
Example 5: Finding Substrings
- Create a string variable and initialize it with a value.
- Use the
strpos
function to find a substring. - Print the position of the found substring.
PHP Program
<?php
$str = "Hello, world!";
$pos = strpos($str, "world"); // Finding substring
if ($pos !== false) {
echo "Found 'world' at position: $pos\n";
} else {
echo "Substring not found\n";
}
?>
Output
Found 'world' at position: 7
Example 6: String Length
- Create a string variable and initialize it with a value.
- Use the
strlen
function to get the length of the string. - Print the length of the string.
PHP Program
<?php
$str = "Hello, world!";
echo "Length of the string: " . strlen($str);
?>
Output
Length of the string: 13