Strings are sequences of characters used to represent text. PHP offers a variety of functions and techniques for manipulating and working with strings.

String Functions

PHP provides numerous built-in functions for handling strings.

  • strlen(): Returns the length of a string.
  $length = strlen("Hello, World!"); // 13
  
  • strtoupper(): Converts a string to uppercase.
  $upper = strtoupper("hello"); // HELLO
  
  • strtolower(): Converts a string to lowercase.
  $lower = strtolower("HELLO"); // hello
  
  • strpos(): Finds the position of the first occurrence of a substring.
  $position = strpos("Hello, World!", "World"); // 7
  
  • substr(): Returns a part of a string.
  $part = substr("Hello, World!", 7, 5); // World
  
  • str_replace(): Replaces all occurrences of a substring with another substring.
  $replaced = str_replace("World", "PHP", "Hello, World!"); // Hello, PHP!
  
  • trim(): Removes whitespace from the beginning and end of a string.
  $trimmed = trim("   Hello, World!   "); // Hello, World!
  

String Concatenation

String concatenation is the process of joining two or more strings together.

  • Concatenation Operator (.):
  $greeting = "Hello";
$name = "World";
$message = $greeting . ", " . $name . "!"; // Hello, World!
  
  • Concatenation Assignment (.=):
  $message = "Hello";
$message .= ", World!"; // Hello, World!
  

String Interpolation

String interpolation allows you to embed variables inside double-quoted strings.

  • Using Double Quotes:
  $name = "World";
$message = "Hello, $name!"; // Hello, World!
  
  • Complex Expressions:
  $age = 30;
$message = "You are {$age} years old."; // You are 30 years old.
  

Regular Expressions

Regular expressions are patterns used to match character combinations in strings. PHP provides functions to work with regular expressions.

  • preg_match(): Performs a regular expression match.
  $pattern = "/World/";
$subject = "Hello, World!";
$match = preg_match($pattern, $subject); // 1 (true)
  
  • preg_replace(): Performs a regular expression search and replace.
  $pattern = "/World/";
$replacement = "PHP";
$subject = "Hello, World!";
$result = preg_replace($pattern, $replacement, $subject); // Hello, PHP!
  
  • preg_split(): Splits a string by a regular expression.
  $pattern = "/[\s,]+/";
$subject = "Hello, World! How are you?";
$parts = preg_split($pattern, $subject); // Array ( [0] => Hello [1] => World [2] => How [3] => are [4] => you? )
  

Strings are a fundamental aspect of PHP programming, and mastering string functions, concatenation, interpolation, and regular expressions will enhance your ability to manipulate and process text data effectively.