PHP String Interview Questions & Answers

PHP string interview questions: strlen() vs mb_strlen(), strstr(), str_replace(), trim(), ucwords(), substr_count(), single vs double quotes, and finding or replacing text in a string.

What are the different data types in PHP?

The PHP manual lists ten primitive data types in three groups.

GroupTypeExample
Scalarstring“Hello PHP!”
Scalarinteger2567
Scalarfloat (double)1.5 or 134.153
Scalarbooleantrue or false
Compoundarray[1, 2, 3]
CompoundobjectAn instance of a class
CompoundcallableA function that can be called
CompounditerableAn array or an object that can be looped
SpecialNULLA variable with no value
SpecialresourceA reference to an outside thing, like an open file

In PHP you do not write the type when you create a variable. PHP picks it from the value. You can check it with var_dump() or gettype(). Learn all of them with examples in PHP Data Types.

How will you concatenate two strings in PHP?

To join (concatenate) two strings in PHP, use the dot operator (.). To add text at the end of an existing variable, use .=.

<?php
$first = "Hello";
$second = "World";

echo $first . " " . $second . "<br>";

$text = "Hello";
$text .= " PHP";
echo $text . "<br>";

echo "$first $second";
?>

Output:

Tutorials Class - Output Window

Hello World
Hello PHP
Hello World

The last line puts the variables inside double quotes, which also works. Remember that the plus sign (+) does not join strings in PHP like in JavaScript, it tries to add numbers. Read more in PHP String Handling.

What is the difference between single quote and double quote string in PHP?

In PHP a string can be written in single quotes or double quotes. They work differently:

Single quotes (‘ ‘)Double quotes (” “)
Text is used exactly as writtenVariables inside are replaced with their values
Only \' and \\ are specialEscape codes like \n, \t and \" work
Good for plain textGood when you need variables inside the text
<?php
$name = "Robin";

echo 'Hello $name' . "<br>";
echo "Hello $name" . "<br>";
echo "Price: {$name}s";
?>

Output:

Tutorials Class - Output Window

Hello $name
Hello Robin
Price: Robins

The curly braces in the last line mark where the variable name ends.

Note: You may read that single quotes are faster. The difference is so tiny that you will never notice it, so choose by need, not by speed. For long text on many lines use heredoc (like double quotes) or nowdoc (like single quotes). See PHP String Handling.

Why we use PHP String functions trim(), ltrim() and rtrim()?

These functions remove white spaces (or other characters that you give) from the ends of a string. They are useful to clean the input of a form.

FunctionRemoves from
trim()Both sides
ltrim()Left side (start)
rtrim()Right side (end)
<?php
echo "[" . trim("  Welcome  ") . "]<br>";
echo trim("--Hello--", "-") . "<br>";
echo ltrim("007", "0") . "<br>";
echo rtrim("Hello!!!", "!");
?>

Output:

Tutorials Class - Output Window

[Welcome]
Hello
7
Hello

The second parameter is a list of characters to remove. If you skip it, PHP removes spaces, tabs, new lines and a few more invisible characters. These functions do not remove spaces from the middle of a string, see how to remove all white spaces.

What PHP Function is used to find position of a string?

Use the strpos() function. It returns the position of the first occurrence of a text inside a string, or false if the text is not found. The counting starts from 0.

<?php
echo strpos("I like apple and banana", "apple");
?>

Output:

Tutorials Class - Output Window

7

The word “apple” starts at position 7, because “I like ” has 7 characters (0 to 6). Because the result can be 0 for a match at the start, always check with !== false. Learn more in PHP strpos() Function and how to check if a string contains a substring.

What is the use of ucwords() PHP String function?

ucwords() changes the first letter of each word of a string to a capital letter. The rest of the letters are not changed.

<?php
echo ucwords("hello world from php") . "<br>";

// Different word separator
echo ucwords("hello-world foo", "-") . "<br>";

// Make the other letters small first
echo ucwords(strtolower("PHP TUTORIAL"));
?>

Output:

Tutorials Class - Output Window

Hello World From Php
Hello-World foo
Php Tutorial

By default words are separated by a space, tab or new line. Use the second parameter to give your own separators. To change only the first letter of the whole string use ucfirst().

What is the use of str_replace() PHP String function?

str_replace() searches a string for some text and replaces it with new text. It replaces all matches.

<?php
echo str_replace("Hello", "Hi", "Hello World, Hello PHP");
?>

Output:

Tutorials Class - Output Window

Hi World, Hi PHP

It is case-sensitive. For a case-insensitive replace use str_ireplace(). See more examples in how to replace a part of a string in PHP.

How to find String Length in PHP?

Use the strlen() function. It returns the length of a string. Spaces and special characters are counted too.

<?php
echo strlen("Hello world!");
?>

Output:

Tutorials Class - Output Window

12

strlen() counts bytes, so for non-English text (like Hindi) or emoji use mb_strlen(). See strlen() vs mb_strlen().

How can we remove the white spaces from string in PHP?

It depends on which spaces you want to remove.

NeedFunction
Remove spaces from both endstrim()
Remove spaces from the left side onlyltrim()
Remove spaces from the right side onlyrtrim()
Remove all spaces everywherestr_replace(" ", "", $text)
Remove spaces, tabs and new lines everywherepreg_replace("/\s+/", "", $text)
<?php
echo "[" . trim("  Hello PHP  ") . "]<br>";
echo str_replace(" ", "", "a b c") . "<br>";
echo preg_replace('/\s+/', '', " a \n b\tc ");
?>

Output:

Tutorials Class - Output Window

[Hello PHP]
abc
abc

The trim functions can also remove other characters, see why we use trim(), ltrim() and rtrim().

How to count the number of words in a string in PHP?

Use the str_word_count() function. It returns how many words are in a string.

<?php
echo str_word_count("Hello world, welcome to Tutorials Class");
?>

Output:

Tutorials Class - Output Window

6

If you pass 1 as the second parameter, it returns the words in an array instead of the count.

<?php
$words = str_word_count("Learn PHP today", 1);

print_r($words);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Learn
[1] => PHP
[2] => today
)

str_word_count() counts only letters, so numbers are not counted as words, and it does not work well for non-English text. For such text, use count(explode(" ", $text)) or preg_split().

How to replace a part of a string in PHP?

Use the str_replace() function. It replaces all matches of a search text with a new text. The syntax is str_replace(search, replace, subject).

<?php
echo str_replace("world", "Dolly", "Hello world!") . "<br>";

// Count how many replacements were done
$text = str_replace("a", "A", "banana", $count);
echo $text . " (" . $count . " replaced)<br>";

// Case-insensitive replace
echo str_ireplace("WORLD", "PHP", "Hello world!");
?>

Output:

Tutorials Class - Output Window

Hello Dolly!
bAnAnA (3 replaced)
Hello PHP!

str_replace() is case-sensitive, use str_ireplace() when the case does not matter. To replace only by position, use substr_replace(). Related: What is the use of str_replace()?.

How to check if a string contains a substring in PHP?

From PHP 8 use str_contains(). It returns true or false. In older versions use strpos(), which returns the position of the match or false.

<?php
$text = "Hello world!";

var_dump(str_contains($text, "world"));
var_dump(strpos($text, "Hello"));
?>

Output:

Tutorials Class - Output Window

bool(true)
int(0)

Look at the second result. The word “Hello” is at position 0, and 0 is also treated as false in a normal comparison. This is the most common mistake with strpos(), so always compare with !==.

<?php
$text = "Hello world!";

if (strpos($text, "Hello") == false) {
    echo "Wrong: says not found<br>";
}

if (strpos($text, "Hello") !== false) {
    echo "Correct: found";
}
?>

Output:

Tutorials Class - Output Window

Wrong: says not found
Correct: found

Both functions are case-sensitive. Learn more in PHP strpos() Function.

What is the use of substr_count() in PHP?

The substr_count() function counts how many times a small text (substring) is found in a bigger string.

<?php
echo substr_count("hello world, hello PHP", "hello") . "<br>";

// Overlapping matches are not counted twice
echo substr_count("aaa", "aa");
?>

Output:

Tutorials Class - Output Window

2
1

  • It is case-sensitive. “Hello” and “hello” are different.
  • It does not count overlapping matches.
  • To count the words of a string use str_word_count(), and to count array elements use count().

What is the difference between strlen() and mb_strlen() in PHP?

strlen() returns the length of a string in bytes. mb_strlen() returns the length in characters. For English letters both are same, but for other languages they are different, because one character can use many bytes.

<?php
$english = "PHP";
$hindi = "नमस्ते";

echo strlen($english) . "<br>";
echo strlen($hindi) . "<br>";
echo mb_strlen($hindi, "UTF-8");
?>

Output:

Tutorials Class - Output Window

3
18
6

The Hindi word has 6 characters, but it takes 18 bytes in UTF-8. So use mb_strlen() whenever the text can have non-English letters, emoji or accents. It needs the mbstring extension, which is enabled in most servers.

What is the use of strip_tags() in PHP?

The strip_tags() function removes HTML and PHP tags from a string. Only the tags are removed, the text inside them stays.

<?php
echo strip_tags("<b>Hello</b> <i>PHP</i>");
?>

Output:

Tutorials Class - Output Window

Hello PHP

You can keep some tags by passing them as second parameter. Here we allow only the bold tag, and we use htmlspecialchars() just to show the HTML code as text.

<?php
$text = "<p><b>Hello</b> <i>PHP</i></p>";

echo htmlspecialchars(strip_tags($text, "<b>"));
?>

Output:

Tutorials Class - Output Window

<b>Hello</b> PHP

Note: strip_tags() is not a full protection for XSS. The text inside a script tag stays as text, and attributes of allowed tags are not checked. To print user data safely use htmlspecialchars(), see PHP Security Tips.

What is the difference between strstr() and stristr() in PHP?

Both functions find the first match of a text inside a string and return the part of the string from that match to the end. The difference is that strstr() is case-sensitive, and stristr() is case-insensitive (it ignores upper or lower case).

<?php
$email = "sonia@example.com";

echo strstr($email, "@") . "<br>";
echo strstr($email, "@", true) . "<br>";

var_dump(strstr("Hello World", "world"));
echo stristr("Hello World", "world");
?>

Output:

Tutorials Class - Output Window

@example.com
sonia
bool(false)
World

The third parameter true returns the part before the match. If there is no match, both functions return false. When you only want to know if a text exists, str_contains() is simpler.

What is the difference between explode() and implode() in PHP?

explode() breaks a string into an array. implode() joins the elements of an array into a string. They do opposite work.

explode()implode()
String to arrayArray to string
explode(separator, string)implode(separator, array)
Splits at every separatorPuts the separator between elements
<?php
$text = "apple,banana,cherry";

$fruits = explode(",", $text);
print_r($fruits);

echo implode(" - ", $fruits);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => apple
[1] => banana
[2] => cherry
)
apple – banana – cherry

Learn more in PHP explode() Function and PHP implode() Function.