PHP Strings

This PHP Strings tutorial helps you learn how to create strings in PHP. So, let us start!

 

What are PHP Strings?

PHP Strings are a collection of alphanumeric characters, enclosed in single quotes for simple string data and in double-quotes for complex string data. 

You can create a string in PHP in multiple ways. Let's start with the simplest way,

<?php

$srt1 = "This is a String";
$str2 = 'This is also a String';

?>

A string can be defined by using double quotes("") as well as single quotes('').

<?php

$srt1 = "This is "a" String";
$str2 = 'This is also 'a' String';

?>

 

In case a string has both a single or double quote in it, then the above string definitions will result in an error because you cannot include a double quote in the string in case the string has been defined inside double-quotes.

But this definition will work if the string contains double quotes, but the string has been defined using single quotes and vice versa. For instance,

<?php

// string inside double quotes, with a single quote
$srt1 = "This is 'a' String";

// string inside single quotes, with a double quote
$str2 = 'This is also "a" String';

?>

 

Another simple technique to deal with the quotes problem is called Escaping Special Character, which can be done using a backslash.

Let's take an example,

<?php

// escaping double quote using backslash
$srt1 = "I"ll handle this.";

// escaping single quote using backslash
$str2 = 'I'll handle this.';

echo $str1;
echo "n";  // new line
echo $str2;

?>

Output:

I"ll handle this.
I'll handle this.

 

The above-mentioned examples show that declaring and defining a string variable in PHP 5 is very simple. You simply have to be careful of the quotes and a few other special characters such as $. So, let us consider an example for $ a special character also.

<?php

// string with $
$srt1 = "pas$word";

echo $str1;

?>

Output:

NOTICE : Undefined variable
pas

 

Running the code above will store only the part of the string before the $ symbol in the variable, while it will treat $word as a variable that is not assigned any value; as a result, PHP prints a NOTICE. Now let us try to use a backslash to escape it,

<?php

// string with escaped $
$srt1 = "pas$word";

echo $str1;

?>

Output:

pas$word

 

The syntax here doc is the best and most simple technique that you can use for defining a multiline string. You can use this method to create strings with one or more lines without string concatenation.

Also, if here doc methodology has been used for defining strings, there is no requirement to escape double or single quotes.

Let's take an example:

<?php

$str = <<< EOT
    Take a right from the T point,
    and the go straight to fins the "Shop"
EOT;

echo $str;

?>

Output:

Take a right from the T point, and the go straight to fins the "Shop"

 

Here EOT is the abbreviation for the end of the text, which means nothing. A multiline string's start and end are marked by these three characters.

EOF or maybe SQL can be used in case you use this to define your multiline SQL query, like the below-mentioned example,

<?php

$tablename = "products";

$str = <<< SQL
    Select * from $tablename
    Where product_name = "widgets"
SQL;

echo $str;

?>

Output:

Select * from products Where product_name = "widgets"

 

In the Nowdoc method of creating a string, the string is not parsed; therefore, in case you wish to add a value to your string using some other variable`, the way we did in the above-mentioned SQL query string, you cannot do that with Nowdoc.

Let's take an exmple,

<?php

$hername = "Selena";

$str = <<< 'LOV'
    This is my declaration of love,
    for $hername
LOV;

echo $str;

?>

Output:

This is my declaration of love, for $hername

 

Printing the String variable

Printing string variables are simple. Let us consider two examples; in the first, we will use the echo method only to print the string variable. In the second example, a string variable will be appended with some other text in the echo method and will be enclosed in single and double-quotes.

<?php

$language_name = "PHP";

// only the string variable
echo $language_name;

// for new line
echo "n";

// string variable with text and single quote
echo ' I love $language_name,';

echo "n";

// string variable with text and double quote
echo " I love, $language_name";

?>

Output:

PHP
I love, PHP
I love you, PHP

 

The difference is that single quotes do not parse the text inside it; as a result, the variable is not translated into its value, while in the case of double quotes, it is translated into its value.

 

PHP String Functions

Now let us learn about the in-built PHP functions for string processing.

  1. strlen($str)
  2. str_word_count($str)
  3. strrev($str)
  4. strpos($str, $text)
  5. str_replace($replacethis, $replacewith, $str)
  6. ucwords($str) 
  7. strtoupper($str)
  8. strtolower($str)
  9. str_repeat($str, $counter)
  10. strcmp($str1, $str2) 
  11. substr($str, $start, $length) 
  12. trim($str, charlist) 
  13. explode(separator, $str, $limit) 
  14. implode(separator, $arr) 
  15. nl2br($str)

 

strlen($str)

The strlen($str) function will return the length of the string or the number of characters in the string, including whitespaces.

<?php

$str = "Welcome to Developerstutorial.com";

// using strlen in echo method
echo "Length of the string is: ". strlen($str);

?>

Output:

Length of the string is: 33

 

str_word_count($str)

The str_word_count($str) function will return the number of words in the string. This function can be used in form field validation for some simple validations.

<?php

$str = "Welcome to Developerstutorial.com";

// using str_word_count in echo method
echo "Number of words in the string are: ". str_word_count($str);

?>

Output:

Number of words in the string are: 3

 

strrev($str)

The strrev($str) function is used for reversing a string.

Let's understand through an example,

<?php

$str = "Welcome to Developerstutorial";

// using strrev in echo method
echo "Reverse: ". strrev($str);

?>

Output:

Reverse: lairotutsrepoleveD ot emocleW

 

strpos($str, $text)

You can use the strpos($str, $text) function for finding the position of any text/word in a given string. The string can also assign index values to the characters stored in it, starting from zero.

<?php

$str = "Welcome to Developerstutorial";

// using strpos in echo method
echo "Position of 'Developerstutorial' in string: ". strpos($str, 'Developerstutorial');

?>

Output:

Position of 'Developerstutorial' in string: 11

 

str_replace($replacethis, $replacewith, $str)

You can use the str_replace($replacethis, $replacewith, $str) function for replacing a part of the string with some text. When you use this function, the part of the string you want to replace is the first argument, the new text you want to include is the second argument, and the last argument is the string variable itself.

<?php

$str = str_replace("Developerstutorial", "Developerstutorial.com", "Welcome to Developerstutorial");

echo $str;

?>

Output:

Welcome to Developerstutorial.com

 

ucwords($str)

You can use the ucwords($str) function to format the string. This function will convert the first letter/character of every word in the string to uppercase.

<?php

$str = "welcome to php tutorial";

echo ucwords($str);

?>

Output:

Welcome To Php Tutorial

 

strtoupper($str)

You can use the strtoupper() method for converting every letter/character of every word of the string to uppercase.

<?php

$str = "welcome to php tutorial";

echo strtoupper($str);

?>

Output:

WELCOME TO PHP TUTORIAL

 

strtolower($str)

You can use the strtolower($str) function for converting every letter/character of a string to lowercase.

<?php

$str = "WELCOME TO PHP TUTORIAL";

echo strtolower($str);

?>

Output:

welcome to php tutorial

 

str_repeat($str, $counter)

You can use the str_repeat($str, $counter) function for repeating a string a given number of times. Here the string will be the first argument, and the number of times the string should be repeated is the second argument.

<?php

$str = "welcome to php tutorial";

echo str_repeat($str, 4);

?>

Output:

welcome to php tutorialwelcome to php tutorialwelcome to php tutorialwelcome to php tutorial

 

strcmp($str1, $str2)

You can use the strcmp($str1, $str2) function for comparing two strings. The comparison will be done alphabetically. In case the first string is greater than the second string, then the result will be greater than 0. In case the first string is equal to the second string, then the result will be equal to 0, and in case the second string is greater than the first string, the result will be less than 0.

<?php

$str1 = "php is a widely-used open source scripting language";
$str2 = "php";

// comparing str1 and str2
echo strcmp($str1, $str2);
echo "n";

// comparing str2 and str1
echo strcmp($str2, $str1);
echo "n";
// comparing str1 with str1
echo strcmp($str1, $str1);

?>

Output:

48 -48 0

 

substr($str, $start, $length)

You can use the substr($str, $start, $length) function for taking out a part of the string(substring), beginning from a particular position, of a specific length.

Here string itself is the first argument, the starting index of the substring to be extracted is the second argument, and the third argument is the length of the substring to be extracted.

<?php

$str = "php is a widely-used open source scripting language";

echo substr($str, 11, 12);

?>

Output:

dely-used op

 

trim($str, charlist)

You can use the trim($str, charlist) function for removing extra whitespaces from a string's beginning and the end. Charlist, the second argument, is optional. As the second argument, you can provide a list of characters, just like a string, for trimming/removing those characters from the main string.

<?php

$str1 = "   Hello Developers   ";

echo trim($str1) . "<br/>";

$str2 = "Hello Hello";

echo trim($str2,"Heo");

?>

Output:

Hello Developers
llo Hell

As seen in the output, extra whitespaces are removed from the beginning and end. Moreover, in the second case, the characters specified are removed from the string's beginning and end.

 

explode(separator, $str, $limit)

You can use the explode(separator, $str, $limit) function for breaking a string, creating an array of the string's broken parts, and returning the array. The first argument, separator, specifies where the string should be broken from. It can be a space, hyphen(-), or any other character.

The string itself is the second argument of this function, and the limit is the third argument which defines the number of array elements to return. The third argument is optional.

<?php

$str = "Its a beautiful day, while learning on developerstutorial";
    
// we can directly print the result of explode
print_r(explode(" ", $str));

?>

Output:

Array ( [0] => Its [1] => a [2] => beautiful [3] => day, [4] => while [5] => learning [6] => on [7] => developerstutorial )

 

implode(separator, $arr)

You can use the implode(separator, $arr) function for forming a string using the array elements from the array provided and then joining them using the separator.

<?php

$arr = array("Its", "a", "beautiful", "day");

// <br> is used to jump to next line
echo implode(" ", $arr) . "<br>";
echo implode("-", $arr) . "<br>";
echo implode("/", $arr) . "<br>";

?>

Output:

Its a beautiful day
Its-a-beautiful-day
Its/a/beautiful/day

 

nl2br($str)

You can use the nl2br($str) function for changing line break or n to the HTML tag for line break, that is <br>.

The nl2br($str) function is helpful in formatting string data for displaying on HTML pages. The reason is when a multiline form data is submitted, it has n included in the string for line breaks, but when it is displayed on your HTML page, the line breaks will not get rendered because HTML does not understand n.

<?php

echo nl2br("Its anbeautiful day");

?>

Output:

Its a
beautiful day