PHP
PHP introduction
PHP basics
PHP variables
PHP functions
PHP conditions
PHP loops
PHP arrays
PHP OOP
PHP strings
PHP forms
PHP entitites
PHP files
PHP include files
PHP date and time
PHP cookies
PHP databases
PHP sessions
PHP summary

Programming

Programming intro
Java

Markup

First webpage guide
HTML
XHTML

Browser scripting

Javascript
VBScript
AJAX

Server scripting

ASP

Making money online

Make money online

PHP strings

A String is a grouping of characters sorrounded by double quotes such as "this is a string".

Strings are an important part of PHP. But there is much more that can be done with them than just printing them onto a webpage. PHP provides many powerful String functions which can be used to manipulate your text in many ways.

This lesson focuses on:

Creating strings

You can create a string by declaring a string variable. The value of a string variable should be text sorrounded by double quotes.

Syntax:

$varName = "string value";

Example:

<?php

$sentence = "The giraffe is an interesting animal.";

?>

Printing strings

You can print a string by referencing the variable which stores the strings value with a print or echo statement. The name of the variable can be sorrounded in double quotes or not.

Syntax:

print $varName;
print "$varName";

echo $varName;
echo "$varName";

Example:

<?php

//declare some strings
$sentence1 = "The giraffe is an interesting animal.";
$sentence2 = "PHP is a scripting language.";

//print the value of the first string
print $sentence1;

//skip a line
echo "<br />";

//print the value of the second string
print "$sentence2";
?>

Output:

The giraffe is an interesting animal.
PHP is a scripting language.

Joining strings

You can join two or more strings into one using the dot ( . ) operator. Using this operator you can either print two or more strings together or you can combine two or more strings into one. Joining two or more strings is known as concatenation.

Syntax:

$aString = $text1 . $text2 . "text" . " more text"

print "$text1" . "$text2" . "text" . "text"

Example:

<?php

//declare some strings
$fragment1 = "The giraffe is ";
$fragment2 = "an interesting animal.";

//declare a third string and join the first
//two strings into it
$sentence1 = $fragment1 . $fragment2;

//print the value of $sentence1
//which is a combination of $fragment1 and $fragment2
print $sentence1;

//skip a line
echo "<br />";

//print four strings together
print "PHP is " . "a scripting " . "language" . ".";
?>

Output:

The giraffe is an interesting animal.
PHP is a scripting language.

String functions

PHP contains several built-in string functions that you can use to manipulate your text in many ways.

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments