- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Strings in PHP
In this part of the PHP programming tutorial, we will work with string data in more detail.
Strings are very important data types in computer languages. That is why we dedicate a whole chapter to working with strings in PHP.
String literals
A string literal is the notation for representing a string value within the text of a computer program. In PHP, strings can be created with single quotes, double quotes or using the heredoc or the nowdoc syntax.
literals.php
<?php $a = "PHP"; $b = 'PERL'; echo $a, $b; ?>
In this code example, we create two strings and assign them to $a
and $b
variables. We print them with the echo
keyword. The first string is created with the double quote delimiters, the second one with single quotes.
The next example will create a string with a heredoc syntax. The heredoc preserves the line breaks and other whitespace (including indentation) in the text. The heredoc is created with <<<
followed by a delimiting identifier, followed, starting on the next line, by the text to be quoted, and then closed by the same identifier on its own line. The closing identifier must not be indented. It can only contain alphanumeric characters and underscores, and must start with a non-digit character or underscore.
heredoc.php
<?php $str = <<<TEXT "That is just as I intended." Vautrin said. "You know quite well what you are about. Good, my little eaglet! You are born to command, you are strong, you stand firm on your feet, you are game! I respect you." TEXT; echo $str, "\n"; ?>
The example prints an example of a direct speech.
$ php heredoc.php "That is just as I intended." Vautrin said. "You know quite well what you are about. Good, my little eaglet! You are born to command, you are strong, you stand firm on your feet, you are game! I respect you."
This is the output of the example.
A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. A nowdoc is identified with the same <<<
sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'TEXT'.
nowdoc.php
<?php $str = <<<'TEXT' Fear is among the greatest obstacles which prevent us from enjoying life to its fullest extent. Since of the most commonly held fears among people are the fear of heights and the fear of falling from heights. Rock climbing is a fantastic way to conquer these fears. TEXT; echo $str, "\n"; ?>
The example prints three sentences using the nowdoc syntax.
$ php nowdoc.php Fear is among the greatest obstacles which prevent us from enjoying life to its fullest extent. Since of the most commonly held fears among people are the fear of heights and the fear of falling from heights. Rock climbing is a fantastic way to conquer these fears.
This is the output of the nowdoc.php
script.
Interpolation
Variables are interpolated in strings enclosed by double quotes.
interpolation.php
<?php $quantity = 5; echo "There are $quantity roses in the vase\n"; ?>
The $quantity
variable is replaced with its value in the string output.
$ php interpolation.php There are 5 roses in the vase
This is the output of the interpolation.php
script.
Curly braces can be used when the variable name is next to another character.
curlybraces.php
<?php $quantity = 5; $item_name = "rose"; echo "There are $quantity {$item_name}s in the vase\n"; ?>
Without the curly braces, the PHP interpreter would look for the $item_names variable, which does not exist.
$ php curlybraces.php There are 5 roses in the vase
This is the output of the curlybraces.php
script.
String concatenation
PHP uses the dot .
operator to concatenate strings.
php > echo "PHP " . "language\n"; PHP language
The example concatenates two strings.
php > $a = "Java "; php > $a .= "language\n"; php > echo $a; Java language
PHP also supports the .=
compound operator.
Escape characters
An escape character is a single character designated to invoke an alternative interpretation on immediately subsequent characters in a character sequence.
php > echo " bbb\raaa"; aaabbb
The carriage return \r
is a control character for end of line return to the beginning of line.
strophe.php
<?php echo "Incompatible, it don't matter though\n'cos someone's bound to hear my cry\n"; echo "Speak out if you do\nYou're not easy to find\n"; ?>
The new line is a control characters which begins a new line of text.
$ php strophe.php Incompatible, it don't matter though 'cos someone's bound to hear my cry Speak out if you do You're not easy to find
This is the output of the strophe.php
script.
php > echo "Towering\tinferno\n"; Towering inferno
The horizontal tab puts a space between text.
"Johnie's dog" 'Johnie\'s dog'
Single and double quotes can be nested. Or in case we use only single quotes, we can use the backslash to escape the default meaning of a single quote.
backslash.php
<?php $text = " \"That is just as I intended.\" Vautrin said. \"You know quite well what you are about. Good, my little eaglet! You are born to command, you are strong, you stand firm on your feet, you are game! I respect you.\" "; echo $text; ?>
In this example, we have a multiline text, which includes direct speech. The double quotes are escaped with the backslash character.
php > $var = 233; php > echo "$var"; 233 php > echo "\$var is $var"; $var is 233
The dollar sign $
has also a special meaning in PHP; it denotes a variable. If a variable is used inside a string, it is interpolated, i.e. the value of the variable is used. To echo a variable name, we escape the $
character \$
.
Operations on strings
PHP has a large number of useful useful built-in functions that can be used for working with strings.
echo strlen("Eagle"); # prints 5 echo strtoupper("Eagle"); # prints EAGLE echo strtolower("Eagle"); # prints eagle
Here we use three functions. The strlen()
function returns a number of characters in the string. The strtoupper()
converts characters to uppercase letters, and the strtolower()
converts characters to lowercase letters.
letters.php
<?php $sentence = "There are 22 apples"; $alphas = 0; $digits = 0; $spaces = 0; $length = strlen($sentence); for ($i = 0; $i < $length; $i++) { $c = $sentence[$i]; if (ctype_alpha($c)) $alphas++; if (ctype_digit($c)) $digits++; if (ctype_space($c)) $spaces++; } echo "There are $length characters.\n"; echo "There are $alphas alphabetic characters.\n"; echo "There are $digits digits.\n"; echo "There are $spaces spaces.\n"; ?>
In our example, we have a string sentence. We calculate the absolute number of characters, number of alphabetic characters, digits and spaces in the sentence. To do this, we use the following functions: strlen()
, ctype_alpha()
, ctype_digit()
, and ctype_space()
.
$ php letters.php There are 19 characters. There are 14 alphabetic characters. There are 2 digits. There are 3 spaces.
This is the output of the letters.php
script.
Next, we cover the substr()
function.
echo substr("PHP language", 0, 3); # prints PHP echo substr("PHP language", -8); # prints language
The function returns a part of a string. The first parameter is the specified string. The second parameter is the start of the substring. The third parameter is optional. It is the length of the returned substring. The default is to the return until the end of the string.
The str_repeat()
function repeats a string a specified number of times.
repeat.php
<?php echo str_repeat("#", 18); echo "\nProject Neurea\n"; echo "Priority high\n"; echo "Security maximum\n"; echo str_repeat("#", 18); echo "\n"; ?>
We use the str_repeat()
function to create two lines of the #
character.
$ php repeat.php ################## Project Neurea Priority high Security maximum ##################
This is the output of the repeat.php
script.
In the next example, we will randomly modify a string.
shuffling.php
<?php $string = "ZetCode"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; ?>
The str_shuffle()
randomly shuffles a string.
$ php shuffling.php ZtCeoed eodtCZe toZeeCd oCdeteZ edtCZoe tdeCeoZ oeZdteC
This is a sample output of the shuffling.php
script.
The explode()
function is used to split a string into parts. It returns an array of split string parts.
exploding.php
<?php $nums = "1,2,3,4,5,6,7,8,9,10,11"; $vals = explode(",", $nums); $len = count($vals); echo "There are $len numbers in the string\n"; ?>
We have integers within a string separated by comma character. We count the number of integers.
$vals = explode(",", $nums);
Here we split the text with the explode()
function. The function will cut a string into pieces whenever it finds the dot ,
character.
$ php exploding.php There are 11 numbers in the string
Output of the example.
teams1.php
<?php echo "Ajax Amsterdam" . " - " . "Inter Milano " . "2:3\n"; echo "Real Madridi" . " - " . "AC Milano " . "3:3\n"; echo "Dortmund" . " - " . "Sparta Praha ". "2:1\n"; ?>
We concatenate strings with the dot operator.
$ php teams1.php Ajax Amsterdam - Inter Milano 2:3 Real Madridi - AC Milano 3:3 Dortmund - Sparta Praha 2:1
The output is not optimal. We will change it so that it looks neater.
teams2.php
<?php $teams = array( array("Ajax Amsterdam", "Inter Milano"), array("Real Madrid", "AC Milano"), array("Dortmund", "Sparta Praha") ); $results = array("2:3", "3:3", "2:1"); $i = 0; foreach ($teams as $team) { echo str_pad($team[0], 14); echo str_pad("-", 3, " ", STR_PAD_BOTH); echo str_pad($team[1], 14); echo str_pad($results[$i], 3, " ", STR_PAD_LEFT); echo "\n"; $i++; } ?>
We improve the output format with the str_pad()
function. It adds a specified string (in our case a space) to the left of the string, to the right or to both sides.
$ php teams2.php Ajax Amsterdam - Inter Milano 2:3 Real Madrid - AC Milano 3:3 Dortmund - Sparta Praha 2:1
We manage to give a nicer formatted output.
Array of chars
A string in PHP is an array of chars.
array_of_chars.php
<?php $site = "zetcode.com"; for ($i=0; $i < strlen($site); $i++) { $o = ord($site[$i]); echo "$site[$i] has ASCII code $o\n"; } ?>
In the example, we iterate through a string and print each character's ASCII code.
$site = "zetcode.com";
A string is defined. It contains eleven characters.
for ($i=0; $i < strlen($site); $i++) { $o = ord($site[$i]); echo "$site[$i] has ASCII code $o\n"; }
We iterate through the string with the for loop. The size of the string is determined with the strlen()
function. The ord()
function returns the ASCII value of a character. We use the array index notation to get a character.
$ php array_of_chars.php z has ASCII code 122 e has ASCII code 101 t has ASCII code 116 c has ASCII code 99 o has ASCII code 111 d has ASCII code 100 e has ASCII code 101 . has ASCII code 46 c has ASCII code 99 o has ASCII code 111 m has ASCII code 109
This is the output of the array_of_chars.php
example.
String formatting
String formatting or string interpolation is dynamic putting of various values into a string.
fruits.php
<?php printf("There are %d oranges and %d apples in the basket.\n", 12, 32); ?>
We use the %d
formatting specifier. The specifier expects an integer value to be passed.
$ php fruits.php There are 12 oranges and 32 apples in the basket.
In the next example, we pass a float and a string value.
height.php
<?php printf("Height: %f %s\n", 172.3, "cm"); ?>
The formatting specifier for a float value is %f
and for a string %s
.
$ php height.php Height: 172.300000 cm
We might not like the fact that the number in the previous example has 6 decimal places by default. We can control the number of the decimal places in the formatting specifier.
height2.php
<?php printf("Height: %.1f %s\n", 172.3, 'cm'); ?>
The decimal point followed by an integer controls the number of decimal places. In our case, the number has exactly one decimal place.
$ php height2.php Height: 172.3 cm
The following example shows other formatting options.
formatting.php
<?php # hexadecimal printf("%x\n", 300); # octal printf("%o\n", 300); # scientific printf("%e\n", 300000); ?>
The first format works with hexadecimal numbers. The x
character formats the number in hexadecimal notation. The o
character shows the number in octal format. The e
character shows the number in scientific format.
$ php formatting.php 12c 454 3.000000e+5
The next example prints three columns of numbers.
columns.php
<?php foreach (range(1,11) as $num) { echo $num , " ", $num*$num, " ", $num*$num*$num, "\n"; } ?>
The numbers are left justified and the output is not neat.
$ php columns.php 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331
To correct this, we use the width specifier. The width specifier defines the minimal width of the object. If the object is smaller than the width, it is filled with spaces.
columns2.php
<?php foreach (range(1,11) as $num) { printf("%2d %3d %4d\n", $num, $num*$num, $num*$num*$num); } ?>
Now the output looks OK. Number 2 says that the first column will be 2 characters wide.
$ php columns2.php 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331
This part of the PHP tutorial covered strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论