PHP Tutorial: PHP Strings

PHP Strings

A string is a series of letters, numbers, special characters and arithmetic values or combination of all, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. The simplest way to create a string is to enclose the string literal (i.e. string characters) in single quotation marks ('), like this:

$my_string = 'Hello World';

We can also use double quotation marks ("). However, single and double quotation marks. Character series(Strings) enclosed in single-quotes are treated almost literally, whereas the strings delimited by the double quotes replaces variables with the string representations of their values as well as specially interpreting certain escape sequences.

The escape-sequence replacements are:

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \" is replaced by a single double-quote (")
  • \\ is replaced by a single backslash (\)

Here's an example to clarify the differences between single and double quoted strings:

<?php
$my_str = 'Quizsolution';
echo "Hello, $my_str!<br>";      // Displays: Hello Quizsolution!
echo 'Hello, $my_str!<br>';      // Displays: Hello, $my_str!	 
echo '<pre>Hello\tWorld!</pre>'; // Displays: Hello\tQuizsolution!
?>

Manipulating PHP Strings:

There are many built-in functions for manipulating strings like calculating the length of a string, find substrings or characters, replacing part of a string with different characters, take a string apart, and many others. Here are the examples of some of these functions.
Calculating the Length of a String
The strlen() function is used to calculate the number of characters inside a string. It also includes the blank spaces inside the string.

<?php
$my_str = 'Welcome to Tutorial Republic';
 
echo strlen($my_str);
?>

Outputs: 28

Counting Number of Words in a String:

The str_word_count() function counts the number of words in a string.

<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';
	 
echo str_word_count($my_str);
?>

Outputs: 9

strtolower() function:
The strtolower() function returns string in lowercase letter.


Syntax
string strtolower ( string $string )  


Example
 

<?php  
$str="My name is KHAN";  
$str=strtolower($str);  
echo $str;  
?>

Output:
my name is khan

strtoupper() function:
The strtoupper() function returns string in uppercase letter.

Syntax
string strtoupper ( string $string )

Example

<?php  
$str="My name is KHAN";  
$str=strtoupper($str);  
echo $str;  
?>  

Output:
MY NAME IS KHAN

 

Next Topic