PHP - Slicing Strings

In PHP, slicing strings means extracting a portion (or substring) of a string. This is typically done using the substr() or mb_substr() functions. Here's how you can use them:

1. Using substr()

$string = "Hello, world!"; $slice = substr($string, 0, 5); // "Hello"

Syntax:

substr(string $string, int $start, ?int $length = null): string
  • $start: Starting position (0-based). Negative values count from the end.

  • $length (optional): Number of characters to extract.

Examples:

echo substr("abcdef", 1); // "bcdef" echo substr("abcdef", 1, 3); // "bcd" echo substr("abcdef", -2); // "ef" echo substr("abcdef", -3, 2); // "de"

2. Using mb_substr() for multibyte strings

Use this if your string contains multibyte characters (e.g., UTF-8, Japanese, emojis).

$string = "こんにちは世界"; // "Hello World" in Japanese $slice = mb_substr($string, 0, 3, "UTF-8"); // "こんにち"