HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Strings

A string is a sequence of characters, like "Hello world!". In PHP, strings are one of the most frequently used data types. Mastering how to search, modify, and format text is essential for building dynamic web applications.


String Functions

PHP comes with hundreds of built-in functions to manipulate strings. Here are the most commonly used ones:

1. strlen() — String Length

The strlen() function returns the length of a string (the number of characters).

<?php
    echo strlen("Hello world!"); // Outputs: 12
?>

2. str_word_count() — Count Words

The str_word_count() function counts the number of words in a string.

<?php
    echo str_word_count("Hello world!"); // Outputs: 2
?>

3. strrev() — Reverse a String

The strrev() function reverses a string.

<?php
    echo strrev("Hello world!"); // Outputs: !dlrow olleH
?>

4. strpos() — Search for Text

The strpos() function searches for a specific text within a string. If a match is found, it returns the character position of the first match. If no match is found, it returns FALSE.

<?php
    echo strpos("Hello world!", "world"); // Outputs: 6
?>

5. str_replace() — Replace Text

The str_replace() function replaces some characters with other characters in a string.

<?php
    echo str_replace("world", "Dolly", "Hello world!"); // Outputs: Hello Dolly!
?>

Double vs. Single Quotes

You can use either single quotes or double quotes for strings, but there is a major difference in how PHP treats them:

  • Double Quotes (" "): PHP will interpolate variables (parse their values) and process escape characters.
  • Single Quotes (' '): PHP treats everything as literal text. It is slightly faster but less flexible.
<?php
    $name = "Alice";
    echo "Hello $name"; // Outputs: Hello Alice
    echo 'Hello $name'; // Outputs: Hello $name
?>

Escape Characters

Sometimes you need to include characters that would otherwise break your string (like quotes) or add formatting like new lines. You can do this using the backslash \.

Character Result
\" Double Quote
\' Single Quote
\$ PHP Variable Sign (prevents interpolation)
\n New Line (visible in source code)
\t Tab
<?php
    $x = "The world's \"best\" developer is you.";
    echo $x;
?>
Pro Tip: When concatenating many strings and variables, using double quotes with variable interpolation usually leads to cleaner and more readable code than using many dots (.).

Key Points to Remember

  • Use strlen() to get characters and str_word_count() for words.
  • strpos() returns the position (starting at 0) of a sub-string.
  • Double quotes parse variables; **single quotes** do not.
  • Use the backslash (\) to escape special characters like quotes or dollar signs.
  • Combine strings using the dot operator (.).