Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Strings

Strings

In PHP, strings are enclosed in either double quotation marks or single quotation marks.

Example

echo "Hello";
echo 'Hello';

Note: There is a significant difference between double quotes and single quotes in PHP.

Double quotes process special characters, while single quotes do not.

Double or Single Quotes?

You can use either double or single quotes, but you should be aware of the differences between them.

Double-quoted strings interpret special characters.

For example, when a variable is included in a double-quoted string, it returns the value of the variable:

Example

Double-quoted string literals process special characters:

$x = "John";
echo "Hello $x";

Single-quoted strings do not perform such actions; they return the string exactly as written, including the variable name.

Example

Single-quoted string literals return the string exactly as it is:

$x = "John";
echo 'Hello $x';

String Length

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

Example

Return the length of the string “Hello world!”:

echo strlen(“Hello world!”);

Word Count

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

Example

Count the number of words in the string “Hello world!”:

echo str_word_count("Hello world!");

Search For Text Within a String

The PHP strpos() function searches for 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.

Example

Search for the text “world” within the string “Hello world!”:

echo strpos(“Hello world!”, “world”);

Tip: The position of the first character in a string is 0 (not 1).