PHP Strings and answers

Looking for a new job? Do not miss to read our PHP Strings and answers. Whether you are a fresher or an experienced, these questions and answers that can help you to crack your interview.

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

Ask Question