PHP String

Working with text and string manipulation in PHP

📝 What are PHP Strings?

Strings are sequences of characters used to store and manipulate text. PHP provides powerful functions to work with strings for tasks like searching, replacing, and formatting text data.


<?php
// Simple string example
$greeting = "Hello, World!";
echo $greeting;
?>
                                    

Output:

Hello, World!

String Functions Overview

📏

Length & Count

Measure string size and count characters

strlen() str_word_count()
🔍

Search & Find

Locate text within strings

strpos() str_contains()
✂️

Modify & Replace

Change and update string content

str_replace() substr()
🔤

Case Conversion

Change text capitalization

strtoupper() strtolower()

🔹 String Length

The strlen() function returns the length of a string, counting all characters including spaces. This is useful for validation and text processing tasks.

<?php
$text = "PHP is awesome!";
echo "Length: " . strlen($text);

$name = "John";
echo "<br>Name length: " . strlen($name);
?>

Output:

Length: 15
Name length: 4

🔹 String Search

Find the position of text within a string using strpos(). It returns the position of the first occurrence or false if not found.

<?php
$sentence = "I love PHP programming";
$position = strpos($sentence, "PHP");
echo "Found at position: " . $position;

// Check if word exists
if (strpos($sentence, "love") !== false) {
    echo "<br>The word 'love' exists!";
}
?>

Output:

Found at position: 7
The word 'love' exists!

🔹 String Replace

Replace parts of a string with str_replace(). This function searches for a value and replaces all occurrences with a new value.

<?php
$text = "I like apples";
$newText = str_replace("apples", "oranges", $text);
echo $newText;

// Replace multiple occurrences
$message = "Hello World! Hello PHP!";
echo "<br>" . str_replace("Hello", "Hi", $message);
?>

Output:

I like oranges
Hi World! Hi PHP!

🔹 Case Conversion

Convert strings to uppercase or lowercase for consistent formatting and comparison. These functions are helpful for case-insensitive operations.

<?php
$text = "Hello World";

// Convert to uppercase
echo strtoupper($text);

// Convert to lowercase
echo "<br>" . strtolower($text);

// Capitalize first letter
echo "<br>" . ucfirst("hello");

// Capitalize each word
echo "<br>" . ucwords("hello world");
?>

Output:

HELLO WORLD
hello world
Hello
Hello World

🔹 Substring Extraction

Extract a portion of a string using substr(). Specify the starting position and optionally the length to extract specific parts of text.

<?php
$text = "Hello World";

// Get first 5 characters
echo substr($text, 0, 5);

// Get last 5 characters
echo "<br>" . substr($text, -5);

// Get from position 6 to end
echo "<br>" . substr($text, 6);
?>

Output:

Hello
World
World

🔹 String Trimming

Remove whitespace or specific characters from the beginning and end of strings. Useful for cleaning user input and formatting data.

<?php
$text = "  Hello World  ";

// Remove spaces from both sides
echo "'" . trim($text) . "'";

// Remove from left only
echo "<br>'" . ltrim($text) . "'";

// Remove from right only
echo "<br>'" . rtrim($text) . "'";
?>

Output:

'Hello World'
'Hello World '
' Hello World'

🔹 String Splitting & Joining

Split strings into arrays or join arrays into strings. These functions are essential for parsing and formatting text data efficiently.

<?php
// Split string into array
$text = "apple,banana,orange";
$fruits = explode(",", $text);
print_r($fruits);

// Join array into string
$colors = ["red", "green", "blue"];
echo "<br>" . implode(", ", $colors);
?>

Output:

Array ( [0] => apple [1] => banana [2] => orange )
red, green, blue

🔹 String Comparison

Compare strings for equality or order. PHP provides multiple comparison functions for different use cases including case-sensitive and case-insensitive comparisons.

<?php
$str1 = "Hello";
$str2 = "hello";

// Case-sensitive comparison
if (strcmp($str1, $str2) == 0) {
    echo "Strings are equal";
} else {
    echo "Strings are different";
}

// Case-insensitive comparison
if (strcasecmp($str1, $str2) == 0) {
    echo "<br>Strings are equal (ignoring case)";
}
?>

Output:

Strings are different
Strings are equal (ignoring case)

🧠 Test Your Knowledge

Which function returns the length of a string?