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.
Here in this article, we will be listing frequently asked PHP Strings and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.
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;
$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!");
The echo and print are basically the same functions, display output data on the screen. However, there are some minor differences between the two such as:
Echo | |
---|---|
It has no return value. | It has a return value of 1, hence can be used in expressions. |
It can work with multiple parameters. | It can function with only one argument at a time. |
It is a bit faster than Print | A bit slower than Print. |
Here’s an example of each Echo and Print to clearly demonstrate their proper usage:
Echo
echo "PHP is Fun!";
print "PHP coding is Fun!";
strtoupper("Best Interview Questiomns");
// Output: BEST INTERVIEW QUESTIONS
You can use nl2br() to insert line break in the string.
nl2br("Best Interview \n Questions");
In PHP, the str_repeat()
function, which is inbuilt is used to repeat a string for a specific number of times. This str_repeat() function creates new strings by repeating the given string ‘n’ number of times as specified.
Here is the syntax of the str_repeat() function: str_repeat(string, repeat)
Here is an example demonstrating the same:
echo str_repeat("BIQ ", 2);
Output
BIQ BIQ
In PHP, we should use the str_word_count() function to count the number of words in a string.
Here’s its syntax: str_word_count ( $string , $returnVal, $chars )
To calculate the number of words in a string, use the function in the following way:
mystring = "This is a function";
print_r(str_word_count($mystring));
To find the position of a character inside a string in PHP, use the strpos() function in the following way:
$pos = strpos($string, $char);
You can use strtolower()
to convert any string to lowercase.
strtolower('Best Interview Questions');
// OUTPUT: best interview questions
Here is a list of the most commonly used PHP String Functions while programming:
string substr(string string, int start[, int length] );
In the above command, it returns with part of the haystack string starting from the point of the needle to the end of the haystack.
Here is an example to show how to strip the HTML tags from a PHP string.
$text = '<p>Test paragraph.</p><a href="#fragment">Other text</a>';
echo strip_tags($text, '<p><a>');Output
Test paragraph.
To limit the characters in a PHP string, use the following code:
if (strlen($str) > 10)
$str = substr($str, 0, 6) . '...';
In the above code, if the str value is greater than 10, the output will display the final result from 0 to the 6th character of the said string.
For this, the str_split()
function can be used. It will convert your string into an array of individual characters where you can enter the start and endpoint of the characters you wish to see.
$str = "Hello";
$arr1 = str_split($str);
print_r($arr1);Output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
)
To find the last character of a PHP string, use the substr() function in the following way:
substr("best interview question", -1);
Output:
n
Suppose we have a
$string = “[Hello there I’m=testing]”
And we want to extract the string placed between the characters between = and ].
Here’s how to do it using PHP string functions:
$str = "[Hello there I’m=testing]";
$from = "=";
$to = "]";echo getStringBetween($str,$from,$to);
function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}Output:
Testing
Here’s a code to replace all the text between two specific characters:
function replace_all_text_between($str, $start, $end, $replacement) {
$replacement = $start . $replacement . $end;
$start = preg_quote($start, '/');
$end = preg_quote($end, '/');
$regex = "/({$start})(.*?)({$end})/";return preg_replace($regex,$replacement,$str);
}
With the help of implode() function in PHP, we can convert arrays into strings. It returns the string.
implode(separator,array);
$arr = array("Best", "Interview", "Question");
echo implode(" ",$arr);OUTPUT
Best Interview Question
To check empty string in PHP, we can use the empty() function.
if(empty($var1)){
// True
} else {
// False
}