PHP Strings

Last update: 30 Mar 2020, 26 QuestionsAsk Question
A Quick Overview of PHP Strings

A string is basically a collection of characters. It is a data type in PHP. A function in PHP is a unit of code that returns a value based on an input or parameter and processing based on the codes.

Functions are basically a set of in a string that is used to manipulate this data type for different uses and requirements. Common PHP String functions include strrev(), strpos(), str_replace() and many more. The basic need of a string function is to help in completing specific tasks relating to a string. It could be reversing, replacing or even searching for text within strings.

PHP String functions are used to manipulate strings in order to perform a specific task/function when the user has given input. This is one of the most commonly used functions in PHP and if you are aspiring for a job as an SDE in PHP, learning string functions is a must.

Below is a list of the most commonly asked interview questions regarding String functions in PHP. Have a look or even download it in PDF format to read it later.

Best PHP Strings And Answers

In PHP, String is a collection of characters. It is one of the data types. We can declare variable and assign string characters to it and we can directly use them with echo statement.



$var1 = “This is good interview Question”
echo $var1;

We can calculate the length of a string with strlen() function in PHP.

$var1 = “This is good interview Question”;
echo strlen($var1);

An example is given below:



$mainString = "I am Bestinterviewquestion.com";
$searchedString = "am";

if( strpos( $mainString, $searchedString ) !== false) {
    echo "\"am\" exists in the main string";

strops() method is used to get the position of the first occurrence of a string inside another string.



$mainString = 'Best Interview Question';
echo strpos($mainString, "Interview");
// OUTPUT : 5

substr() is a substring of PHP. It is an inbuilt function which is used to extract a part of the string.

trim() removes all blank spaces or whitespace or other (specified) characters from both sides of a string.

$var = “ Best Interview Questions ”;
echo $var;

  • ltrim() – It removes whitespace/other specified characters from the left side of a string.
  • rtrim() - It removes whitespace/other specified characters from the right side of a string.



$var = “Best Interview Questions”;

ltrim(“Best”, $var);
rtrim(“Questions”, $var);


We can use str_replace() method to replace a text in a string with another string.



str_replace("interview","interviews","Best interview questions!");

We can use strtoupper() method to convert any string to Uppercase.



strtoupper("Best Interview Questiomns");

You can use nl2br() to insert line break in the string.



nl2br("Best Interview \n Questions");

You can use strtolower() to convert any string to lowercase.



strtolower('Best Interview Questions');
// OUTPUT: best interview questions

Add Review