```html

String Handling - Searching, Replacing, Formatting, and String Library Functions

In programming, a string is a sequence of characters. PHP provides a rich set of functions to manipulate strings, which are essential for various tasks like data validation, user input processing, and generating dynamic content. This section delves into the core string handling capabilities in PHP, focusing on searching, replacing, formatting, and utilizing built-in library functions.

1. Searching within Strings

Finding a specific substring within a larger string is a common requirement. PHP offers several functions for this purpose, each with slightly different behaviors and return values.

1.1. `strpos()` - Find the position of the first occurrence of a substring

The `strpos()` function finds the position of the first occurrence of a substring in a string. It is case-sensitive.

Syntax: `strpos(string $haystack, mixed $needle, int $offset = 0): int|false`

  • $haystack: The string to search within.
  • $needle: The substring to search for.
  • $offset: (Optional) The position from which to start the search. Defaults to 0 (the beginning of the string).

It returns the numerical position (index) of the first occurrence of the substring, starting from 0. If the substring is not found, it returns `false`.

Important Note: Because the position 0 is a valid return value, you must use the strict comparison operator (`===` or `!==`) when checking if the needle was found or not.

Example:

<?php
$text = "Hello world, welcome to the world of PHP!";
$search_term = "world";

$position = strpos($text, $search_term);

if ($position !== false) {
    echo "The word '" . $search_term . "' was first found at position: " . $position;
} else {
    echo "The word '" . $search_term . "' was not found.";
}

// Searching with an offset
$second_position = strpos($text, $search_term, $position + 1);
if ($second_position !== false) {
    echo "<br>The word '" . $search_term . "' was also found at position: " . $second_position;
}
?>

Output: The word 'world' was first found at position: 6
The word 'world' was also found at position: 29

1.2. `stripos()` - Find the position of the first occurrence of a substring (case-insensitive)

Similar to `strpos()`, but `stripos()` performs a case-insensitive search.

Syntax: `stripos(string $haystack, mixed $needle, int $offset = 0): int|false`

Example:

<?php
$text = "Hello World, welcome to the WoRlD of PHP!";
$search_term = "world";

$position = stripos($text, $search_term);

if ($position !== false) {
    echo "The word '" . $search_term . "' was first found (case-insensitive) at position: " . $position;
} else {
    echo "The word '" . $search_term . "' was not found.";
}
?>

Output: The word 'world' was first found (case-insensitive) at position: 6

1.3. `strstr()` / `stristr()` - Find the first occurrence of a substring and return the rest of the string

These functions find the first occurrence of a substring and return the part of the haystack string starting from that occurrence. `strstr()` is case-sensitive, while `stristr()` is case-insensitive.

Syntax:

  • `strstr(string $haystack, mixed $needle, bool $before_needle = false): string|false`
  • `stristr(string $haystack, mixed $needle, bool $before_needle = false): string|false`
  • $before_needle: If set to `true`, it returns the part of the haystack before the first occurrence of the needle.

Example:

<?php
$email = "user@example.com";

// Get the domain name
$domain = strstr($email, '@');
if ($domain !== false) {
    echo "Domain: " . $domain;
}

// Get the username (part before @)
$username = strstr($email, '@', true);
if ($username !== false) {
    echo "<br>Username: " . $username;
}
?>

Output: Domain: @example.com
Username: user

1.4. `str_contains()` - Check if a string contains a substring

Introduced in PHP 8, this function provides a simple boolean check. It's more readable for simply checking existence.

Syntax: `str_contains(string $haystack, string $needle): bool`

Example:

<?php
$message = "The quick brown fox jumps over the lazy dog.";

if (str_contains($message, "fox")) {
    echo "The message contains the word 'fox'.";
}

if (!str_contains($message, "cat")) {
    echo "<br>The message does not contain the word 'cat'.";
}
?>

Output: The message contains the word 'fox'.
The message does not contain the word 'cat'.

2. Replacing Substrings

Replacing parts of a string is crucial for tasks like censoring words, correcting typos, or reformatting data.

2.1. `str_replace()` - Replace all occurrences of a search string with a replacement string

This is the most common string replacement function. It is case-sensitive.

Syntax: `str_replace(mixed $search, mixed $replace, mixed $subject, int &$count = null): mixed`

  • $search: The string or array of strings to search for.
  • $replace: The string or array of strings to replace with. If `$search` and `$replace` are arrays, then each element from `$search` is replaced with the corresponding element from `$replace`. If `$replace` has fewer elements than `$search`, then the extra replacements are made with an empty string. If `$search` is an array and `$replace` is a string, then all search values are replaced with the same replacement string.
  • $subject: The string or array of strings to perform the replacement on.
  • $count: (Optional) If passed, this variable will be filled with the number of replacements performed.

Example:

<?php
$text = "The quick brown fox jumps over the lazy dog. The fox is sly.";
$old_word = "fox";
$new_word = "cat";

$new_text = str_replace($old_word, $new_word, $text, $count);
echo $new_text;
echo "<br>Number of replacements: " . $count;

// Replacing multiple words
$search_array = ["quick", "lazy"];
$replace_array = ["fast", "active"];
$another_text = "The quick brown fox jumps over the lazy dog.";
$modified_text = str_replace($search_array, $replace_array, $another_text);
echo "<br>" . $modified_text;
?>

Output: The quick brown cat jumps over the lazy dog. The cat is sly.
Number of replacements: 2
The fast brown fox jumps over the active dog.

2.2. `str_ireplace()` - Case-insensitive replacement

Similar to `str_replace()`, but performs a case-insensitive search and replace.

Syntax: `str_ireplace(mixed $search, mixed $replace, mixed $subject, int &$count = null): mixed`

Example:

<?php
$text = "Hello World, welcome to the WoRlD of PHP!";
$old_word = "world";
$new_word = "Universe";

$new_text = str_ireplace($old_word, $new_word, $text);
echo $new_text;
?>

Output: Hello Universe, welcome to the Universe of PHP!

2.3. `preg_replace()` / `preg_replace_callback()` - Powerful replacement using regular expressions

For more complex pattern-based replacements, PHP's regular expression functions are indispensable. `preg_replace()` replaces all matches of a pattern (defined by a regular expression) with a replacement string. `preg_replace_callback()` allows you to use a callback function to determine the replacement.

Syntax:

  • `preg_replace(mixed $pattern, mixed $replacement, mixed $subject, int $limit = -1, int &$count = null): mixed`
  • `preg_replace_callback(mixed $pattern, callable $callback, mixed $subject, int $limit = -1, int &$count = null): mixed`

Example (using `preg_replace`):

<?php
// Remove all HTML tags
$html_string = "<p>This is <b>bold</b> text.</p>";
$plain_text = preg_replace('/<[^>]*>/', '', $html_string);
echo $plain_text;

// Replace multiple spaces with a single space
$spaced_text = "This has too many spaces.";
$normalized_text = preg_replace('/\s+/', ' ', $spaced_text);
echo "<br>" . $normalized_text;
?>

Output: This is bold text.
This has too many spaces.

3. String Formatting

Formatting allows you to control the presentation of strings, such as padding, aligning, and converting case.

3.1. Case Conversion Functions

These functions change the case of characters within a string.

  • strtolower(string $string): string: Converts a string to lowercase.
  • strtoupper(string $string): string: Converts a string to uppercase.
  • ucfirst(string $string): string: Converts the first character of a string to uppercase.
  • ucwords(string $string, string $delimiters = " \t\r\n\f\v"): string: Converts the first character of each word in a string to uppercase.

Example:

<?php
$original = "This Is An Example String.";
echo strtolower($original) . "<br>";
echo strtoupper($original) . "<br>";
echo ucfirst($original) . "<br>";
echo ucwords($original) . "<br>";
?>

Output: this is an example string.
THIS IS AN EXAMPLE STRING.
This is an example string.
This Is An Example String.

3.2. Padding Functions

These functions add characters to a string to reach a desired length.

  • str_pad(string $string, int $pad_length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string: Pads string to the right, left, or both sides.

$pad_type can be:

  • STR_PAD_RIGHT (default): Pad with the string to the right (end).
  • STR_PAD_LEFT: Pad with the string to the left (beginning).
  • STR_PAD_BOTH: Pad with the string to both sides.

Example:

<?php
$number = "42";
echo str_pad($number, 5, "0", STR_PAD_LEFT); // Output: 00042
echo "<br>";
$text = "PHP";
echo str_pad($text, 10, "-", STR_PAD_BOTH); // Output: ---PHP----
?>

Output: 00042
---PHP----

3.3. `sprintf()` and `printf()` - Formatted String Output

These functions are powerful for creating formatted strings, similar to C's `sprintf`. `sprintf()` returns the formatted string, while `printf()` outputs it directly.

Common format specifiers include:

  • %s: String
  • %d: Signed decimal integer
  • %f: Floating-point number (e.g., %.2f for 2 decimal places)
  • %x: Hexadecimal number (lowercase)
  • %X: Hexadecimal number (uppercase)

Syntax:

  • `sprintf(string $format, mixed ...$args): string`
  • `printf(string $format, mixed ...$args): int`

Example:

<?php
$name = "Alice";
$age = 30;
$height = 1.65;

// Using sprintf to create a formatted string
$output_string = sprintf("Name: %s, Age: %d, Height: %.2f meters", $name, $age, $height);
echo $output_string;
echo "<br>";

// Using printf to output directly
printf("User %s is %d years old.", "Bob", 25);
?>

Output: Name: Alice, Age: 30, Height: 1.65 meters
User Bob is 25 years old.

4. String Library Functions - A Comprehensive Overview

PHP offers a vast array of string functions. Here are some of the most frequently used ones, categorized for clarity.

4.1. Length and Size

  • strlen(string $string): int: Returns the length of a string (in bytes).
  • mb_strlen(string $string, ?string $encoding = null): int|false: Returns the length of a string using a multi-byte encoding (e.g., UTF-8). Recommended for international characters.

4.2. Extraction and Substrings

  • substr(string $string, int $offset, ?int $length = null): string: Returns a portion of a string.
  • substr_replace(string $string, string $replacement, int $start, ?int $length = null): string: Replaces part of a string.

4.3. Splitting and Joining

  • explode(string $delimiter, string $string, int $limit = PHP_INT_MAX): array: Splits a string by a delimiter into an array.
  • implode(string $glue, array $pieces): string: Joins array elements into a string using a "glue" string. (Alias: `join()`)

Example:

<?php
$csv_data = "apple,banana,cherry";
$fruits_array = explode(",", $csv_data);
print_r($fruits_array);

$joined_string = implode(" | ", $fruits_array);
echo "<br>" . $joined_string;
?>

Output: Array ( [0] => apple [1] => banana [2] => cherry )
apple | banana | cherry

4.4. Trimming Whitespace

  • trim(string $string, string $characters = " \n\r\t\v\0"): string: Removes whitespace (or other characters) from the beginning and end of a string.
  • ltrim(string $string, string $characters = " \n\r\t\v\0"): string: Removes whitespace from the beginning (left side).
  • rtrim(string $string, string $characters = " \n\r\t\v\0"): string: Removes whitespace from the end (right side).

Example:

<?php
$padded_string = " Hello ";
echo "[" . trim($padded_string) . "]"; // Output: [Hello]
echo "<br>";
$url = "http://www.example.com/";
echo rtrim($url, "/"); // Output: http://www.example.com
?>

Output: [Hello]
http://www.example.com

4.5. Comparison

  • strcmp(string $str1, string $str2): int: Binary safe string comparison (case-sensitive). Returns < 0 if $str1 is less than $str2, > 0 if $str1 is greater than $str2, and 0 if they are equal.
  • strcasecmp(string $str1, string $str2): int: Case-insensitive version of `strcmp()`.

4.6. Miscellaneous Useful Functions

  • str_repeat(string $input, int $multiplier): string: Repeats a string a specified number of times.
  • str_shuffle(string $str): string: Randomly shuffles all characters in a string.
  • str_word_count(string $string, int $format = 0, ?string $charlist = null): int|array: Returns information about words used in a string.
  • levenshtein(string $str1, string $str2, int $cost_ins = 1, int $cost_rep = 1, int $cost_del = 1): int: Calculates the Levenshtein distance between two strings (measures how many single-character edits are required to change one word into the other).
  • similar_text(string $first, string $second, float &$percent = null): int: Computes the similarity between two strings.

Exam Tip: `strpos()` vs. `strstr()`

Remember that `strpos()` returns the numerical *position* (index) of the substring, while `strstr()` returns the *substring itself* (or the rest of the string from that point). Always use strict comparison (`===` or `!==`) with `strpos()` and `stripos()` because the position 0 is a valid result.

Exam Tip: `strlen()` vs. `mb_strlen()`

For applications dealing with international characters (like UTF-8 encoded text), always prefer `mb_strlen()` over `strlen()`. `strlen()` counts bytes, which can lead to incorrect lengths for multi-byte characters (e.g., 'é' might be 2 bytes, not 1 character). Ensure the `mbstring` extension is enabled.

Exam Tip: Regular Expressions (`preg_` functions)

While `str_replace` is great for simple replacements, `preg_replace` and its variants unlock immense power for pattern-based manipulation. Understanding basic regular expression syntax is crucial for advanced string handling and security tasks (like sanitizing input).

```