PHP Strings

PHP Strings

In PHP, strings are sequences of characters that are used to store and manipulate text. Strings are one of the most commonly used data types, and PHP provides a variety of functions and operators to work with them.

1. Creating Strings

You can create strings in PHP in two ways: using single quotes (') or double quotes (").

a) Single-quoted Strings

  • Everything inside the single quotes is treated literally, except for escape sequences like \\ and \'.
$name = 'John Doe'; $sentence = 'This is a string.';

b) Double-quoted Strings

  • Double quotes allow for variable interpolation (replacing variables with their values) and special escape sequences.
$name = "John Doe"; $sentence = "Hello, $name!"; // Variable interpolation echo $sentence; // Outputs: Hello, John Doe!
  • In double-quoted strings, escape sequences such as \n (new line), \t (tab), \$ (dollar sign), \" (double quote) can be used.
$example = "Hello\nWorld"; // Outputs: Hello (new line) World echo $example;

Note on Variable Interpolation:

Variable interpolation works only inside double-quoted strings, not inside single-quoted strings.

$age = 25; echo 'Age is $age'; // Outputs: Age is $age (no interpolation) echo "Age is $age"; // Outputs: Age is 25 (interpolated)

2. String Concatenation

To concatenate (combine) two strings in PHP, you use the dot operator (.).

$firstName = "John"; $lastName = "Doe"; $fullName = $firstName . " " . $lastName; echo $fullName; // Outputs: John Doe

You can also use concatenation assignment (.=) to append a string to an existing one.

$message = "Hello"; $message .= " World!"; echo $message; // Outputs: Hello World!

3. Escape Sequences in Strings

PHP supports special escape sequences for both single and double-quoted strings:

a) In Double-quoted Strings:

  • \" – Double quote
  • \\ – Backslash
  • \n – New line
  • \r – Carriage return
  • \t – Tab
  • \$ – Dollar sign
  • \u{X} – Unicode character (where X is the hexadecimal code point)

Example:

$quote = "He said, \"Hello!\""; echo $quote; // Outputs: He said, "Hello!"

b) In Single-quoted Strings:

  • \\ – Backslash
  • \' – Single quote

Example:

$quote = 'It\'s a nice day!'; echo $quote; // Outputs: It's a nice day!

4. String Length

You can use the strlen() function to get the length of a string (number of characters):

$greeting = "Hello, World!"; echo strlen($greeting); // Outputs: 13

5. String Comparison

You can compare two strings using comparison operators (==, ===, !=, !==, <, >, etc.).

  • ==: Checks if two strings are equal (ignores case).
  • ===: Checks if two strings are identical (including case).
  • !=: Checks if two strings are not equal.
  • !==: Checks if two strings are not identical.

Example:

$str1 = "hello"; $str2 = "HELLO"; echo ($str1 == $str2) ? "Equal" : "Not Equal"; // Outputs: Equal (case-insensitive) echo ($str1 === $str2) ? "Identical" : "Not Identical"; // Outputs: Not Identical (case-sensitive)

6. String Functions

PHP has many built-in functions for manipulating strings. Here are some of the most commonly used string functions:

  • strtoupper(): Converts a string to uppercase.

    $text = "hello"; echo strtoupper($text); // Outputs: HELLO
  • strtolower(): Converts a string to lowercase.

    $text = "HELLO"; echo strtolower($text); // Outputs: hello
  • ucfirst(): Capitalizes the first letter of a string.

    $text = "hello"; echo ucfirst($text); // Outputs: Hello
  • ucwords(): Capitalizes the first letter of each word in a string.

    $text = "hello world"; echo ucwords($text); // Outputs: Hello World
  • substr(): Returns a portion of the string.

    $text = "Hello, World!"; echo substr($text, 7, 5); // Outputs: World
  • strpos(): Finds the position of the first occurrence of a substring in a string.

    $text = "Hello, World!"; echo strpos($text, "World"); // Outputs: 7
  • str_replace(): Replaces occurrences of a substring within a string.

    $text = "Hello, World!"; echo str_replace("World", "PHP", $text); // Outputs: Hello, PHP!
  • trim(): Removes whitespace or other predefined characters from both ends of a string.

    $text = " Hello, World! "; echo trim($text); // Outputs: Hello, World!
  • explode(): Splits a string into an array based on a delimiter.

    $text = "apple,banana,orange"; $fruits = explode(",", $text); print_r($fruits); // Outputs: Array ( [0] => apple [1] => banana [2] => orange )
  • implode(): Joins elements of an array into a single string.

    $fruits = ["apple", "banana", "orange"]; echo implode(", ", $fruits); // Outputs: apple, banana, orange

7. Multiline Strings

You can create multiline strings in PHP by using heredoc or nowdoc syntax.

a) Heredoc Syntax:

Heredoc allows you to create a string that spans multiple lines, and variable interpolation works within it.

$name = "John"; $heredoc = <<<EOD Hello, $name! This is a multiline string. EOD; echo $heredoc;

b) Nowdoc Syntax:

Nowdoc is similar to heredoc but does not support variable interpolation.

$nowdoc = <<<'EOD' This is a nowdoc string. Variables like $name won't be replaced. EOD; echo $nowdoc;

8. String Padding

PHP provides functions for padding strings with specific characters.

  • str_pad(): Pads a string to a certain length with a specified character.
    $text = "Hello"; echo str_pad($text, 10, "*"); // Outputs: Hello*****

Conclusion

  • PHP strings are used to handle and manipulate text data.
  • Strings can be created using single quotes or double quotes, each with different behaviors for variable interpolation and escape sequences.
  • PHP provides a wide range of functions to manipulate strings, including string length, comparison, searching, replacing, and padding.
  • You can use heredoc and nowdoc syntax for creating multiline strings in PHP.
  • Mastering PHP strings is essential for effective text manipulation and working with dynamic content.
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close