PHP Strings
A string is a sequence of characters. In PHP, strings are used to store and manipulate text — anything from a single word to an entire paragraph. PHP provides an extensive set of built-in functions for working with strings, making it straightforward to search, modify, format, and display text data.
Creating Strings
PHP strings can be created using single quotes, double quotes, or heredoc syntax.
Single Quotes
Single-quoted strings treat all characters literally. Variables and escape sequences (except \\ and \') are not processed.
<?php
$name = "Alice";
echo 'Hello, $name!'; // Outputs: Hello, $name!
echo 'It\'s a great day'; // Outputs: It's a great day
?>
Double Quotes
Double-quoted strings process variables and escape sequences inside them.
<?php
$city = "Tokyo";
echo "Welcome to $city!"; // Outputs: Welcome to Tokyo!
echo "Line 1\nLine 2"; // \n creates a new line
echo "Tab\there"; // \t creates a tab
?>
Heredoc Syntax
Heredoc is a way to write multi-line strings while still supporting variable interpolation. The content between the identifiers is treated like a double-quoted string.
<?php
$product = "Laptop";
$price = 899;
$description = <<<EOT
Product: $product
Price: $$price
This item is available for immediate shipping.
EOT;
echo $description;
?>
String Length
The strlen() function returns the number of characters in a string, including spaces.
<?php
$text = "Hello, World!";
echo strlen($text); // Outputs: 13
?>
String Case Functions
PHP provides several functions to change the case of characters in a string.
<?php
$text = "pHp Is FuN";
echo strtolower($text); // Outputs: php is fun
echo strtoupper($text); // Outputs: PHP IS FUN
echo ucfirst($text); // Outputs: PHP Is FuN (first letter uppercase)
echo ucwords($text); // Outputs: PHP Is FuN (first letter of each word uppercase)
?>
Searching Inside Strings
strpos() — Finding a Substring
The strpos() function returns the position of the first occurrence of a substring inside a string. Positions start at 0. If the substring is not found, it returns false.
<?php
$sentence = "PHP is a great language";
$pos = strpos($sentence, "great");
echo $pos; // Outputs: 10
if (strpos($sentence, "PHP") !== false) {
echo "Found!";
}
?>
Always use !== false for the check, not != false, because if the substring is at position 0, the function returns 0, which would evaluate as false in a loose comparison.
str_contains() — PHP 8 Shorthand
<?php
$text = "The sky is blue";
if (str_contains($text, "blue")) {
echo "Color found."; // Outputs: Color found.
}
?>
Replacing Parts of a String
<?php
$phrase = "I love Java programming";
$newPhrase = str_replace("Java", "PHP", $phrase);
echo $newPhrase; // Outputs: I love PHP programming
?>
The first argument is the search value, the second is the replacement, and the third is the source string.
Extracting a Portion of a String
The substr() function extracts a portion of a string starting at a given position.
<?php
$text = "Hello, World!";
echo substr($text, 7); // Outputs: World! (from position 7 to end)
echo substr($text, 7, 5); // Outputs: World (5 characters starting at position 7)
echo substr($text, -6); // Outputs: World! (last 6 characters)
?>
Trimming Whitespace
The trim() function removes whitespace from both ends of a string. ltrim() and rtrim() remove from the left or right side only.
<?php
$input = " user input with spaces ";
echo trim($input); // Outputs: user input with spaces
echo ltrim($input); // Outputs: user input with spaces (right space kept)
echo rtrim($input); // Outputs: user input with spaces (left space kept)
?>
Splitting and Joining Strings
explode() — String to Array
<?php
$csv = "apple,banana,cherry,date";
$fruits = explode(",", $csv);
print_r($fruits);
// Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
echo $fruits[1]; // Outputs: banana
?>
implode() — Array to String
<?php
$words = ["PHP", "is", "awesome"];
$sentence = implode(" ", $words);
echo $sentence; // Outputs: PHP is awesome
?>
Repeating and Padding Strings
<?php
echo str_repeat("ha", 3); // Outputs: hahaha
$code = "42";
echo str_pad($code, 5, "0", STR_PAD_LEFT); // Outputs: 00042
?>
Counting Words
<?php
$text = "PHP is a great server-side language";
echo str_word_count($text); // Outputs: 7
?>
Key Points
- Single-quoted strings treat content literally; double-quoted strings process variables and escape sequences.
strlen()returns the character count of a string.strtolower()andstrtoupper()change string case.strpos()finds the position of a substring; use!== falsefor safe comparison.str_replace()replaces text within a string.substr()extracts part of a string by position and length.trim()removes leading and trailing whitespace.explode()splits a string into an array;implode()joins an array into a string.
