PHP Strings. Everything You Need To Know About Strings in PHP

Posted by TotalDC

In this article we will moving further into learning PHP and will talk about PHP strings.

What Is String In PHP

A string as you may know is a group of letters, numbers and special characters or perhaps combination of all. The simplest way to create a string is to enclose the characters in single quotation (‘).

For example string could look like this:

$my_string = 'Hello World';

Just like single quotation, you can use double quotation (“) as well. But keep in mind single and double quotation marks works differently. String in a single quotes are treated almost literally, but the strings in double quotes replaces variables with the string representation of their values as well as specially interpreting certain escape sequences.

Escape Sequences in PHP

The escape sequences are:

  • \n – newline character
  • \r – carriage return character
  • \t – tab character
  • \$ – dollar sign itself ($)
  • \” – single double quote (“)
  • \’ – single quote symbol (‘)
  • \\ – single backslash symbol (\)

And here is an example to make understanding of single and double quote strings easier.

<?php
$my_str = 'World';
print "Hello, $my_str!<br>";      // Result: Hello World!
print 'Hello, $my_str!<br>';      // Result: Hello, $my_str!
 
print '<pre>Hello\tWorld!</pre>'; // Result: Hello\tWorld!
print "<pre>Hello\tWorld!</pre>"; // Result: Hello   World!
print 'I\'ll be back';            // Result: I'll be back
?>

Manipulating PHP Strings

PHP gives you many already built-in functions for manipulating strings. For example calculating the length of a string, replacing part of a string with different characters and many others. Here are 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.

Example:

<?php
$my_str = 'Welcome to Simply Web Stuff';
 
// Outputs: 27
print strlen($my_str);
?>

Counting Number Of Words In A String

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

Example:

<?php
$my_str = 'This is test string';
 
// Outputs: 4
print str_word_count($my_str);
?>

Replace Text In A String

The str_replace() replaces all occurrences of the search text within the target string.

Example:

<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
 
// Display replaced string
print str_replace("facts", "truth", $my_str);
// Result: If the truth do not fit the theory, change the truth.
?>

Reverse A String

The strrev() function reverses a string.

Example:

<?php
$my_str = 'This string is for testing';
 
// Display reversed string
print strrev($my_str);
?>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: