PHP Strings


Strings are text sequences that enable text storage and manipulation. PHP automatically recognizes any text within single quotes (') or double quotes (") as a string.

 


Declaring Strings

<?php
$name1 = "Alice";   // double quotes
$name2 = 'Bob';     // single quotes
?> 

  • Double quotes (") enable variable interpolation and special character parsing within strings.
  • PHP processes single quotes (') as literal strings which results in faster execution but does not support variable interpolation.

String Interpolation

$name = "Alice";
echo "Hello, $name!";  // Output: Hello, Alice!
echo 'Hello, $name!';  // Output: Hello, $name! 

Function Description Example
strlen() Returns string length strlen("PHP") → 3
strtolower() Converts to lowercase strtolower("Hello") → "hello"
strtoupper() Converts to uppercase strtoupper("php") → "PHP"
strpos() Finds position of a substring strpos("Hello World", "World") → 6
str_replace() Replaces text str_replace("World", "PHP", ...)
substr() Returns part of string substr("abcdef", 1, 3) → "bcd"
trim() Removes whitespace from start and end trim(" Hello ") → "Hello"
explode() Splits string into array explode(",", "a,b,c") → [a,b,c]
implode() Joins array into string implode("-", [a,b]) → "a-b"

Example

<?php
$greeting = " Hello World ";

echo strlen($greeting);              // Length: 13
echo trim($greeting);                // "Hello World"
echo strtoupper($greeting);         // " HELLO WORLD "
echo strtolower($greeting);         // " hello world "
echo str_replace("World", "PHP", $greeting); // " Hello PHP "
echo substr($greeting, 1, 5);        // "Hello"
echo strpos($greeting, "World");     // Position: 7
?> 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.