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.
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.
Strings can be created in PHP using single or double quotes:
$str = "Hello, world!";
Strings can also be created using heredoc
syntax:
$str2 = <<
echo
.<?php
$str = "Hello, world!";
echo $str;
?>
Hello, world!
<?php
$str = "Hello";
echo $str[0] . "\n"; // Accessing using array indexing
echo $str[1] . "\n";
?>
H e
<?php
$str = "Hello";
$str[0] = 'J'; // Modifying individual character
$str .= " World!"; // Appending new characters
echo $str;
?>
Jello World!
.
operator.<?php
$str1 = "Hello";
$str2 = " World!";
$str3 = $str1 . $str2; // Concatenating strings
echo $str3;
?>
Hello World!
strpos
function to find a substring.<?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";
}
?>
Found 'world' at position: 7
strlen
function to get the length of the string.<?php
$str = "Hello, world!";
echo "Length of the string: " . strlen($str);
?>
Length of the string: 13