Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL

Home > PHP > Strings and Substringsprinter version

PHP Strings and Substrings

PHP provides library functions to find and extract substrings from source strings.

Extracting Substrings

The substr() function returns a substring from a string. The function accepts as arguments the source string and the start position counted from zero at the beginning of the string.

It also accepts an optional length argument to determine how many characters to return.

Examples of substr()
<?php
    $name = "Georgina";

    // This prints out gina
    echo (substr ($name, 4));

    // This prints out Georgi
    echo (substr ($name, 0, 6));
?>


If a negative start argument is passed then the start point is counted from the end of the source string.

If a negative length argument is passed then this is treated as the end point, counted from the end of the source string.

Examples of substr() With Negative Arguments
<?php
    $name = "Georgina";

    // This prints out orgina
    echo (substr ($name, -6));

    // This prints out org
    echo (substr ($name, -6, -3));
?>


Finding the Position of a Substring

The strpos() function returns the position of the first occurring substring within a source string.

It takes as arguments the source string and the substring and by default starts from the beginning of the source string at zero.

It also allows a third optional argument that adds an offset to the start position.

Example of strpos()
<?php
    $sentence = "Tom, Dick, Harry, and Dick's brother work here.";

    // This prints out 5
    echo (strpos ($sentence, "Dick"));

    // This prints out 22
    echo (strpos ($sentence, "Dick", 11));
?>


The strrpos() function is similar to the strpos() function except ...



Example of strrpos()
<?php
    $sentence = "Tom, Dick, Harry, and Dick's brother work here.";

    // This prints out 22
    echo (strrpos ($sentence, "Dick"));
?>


With all of these functions, false is returned if the substring isn't found within the source string.

Note: If the substring is at the start of the source string then this will return a zero value, which will give the same result as a false value if the equality operator == is used.

Therefore if testing the return value the is-identical operator === should be used.

Extracting a Found Portion of a String

The strstr() function searches for a substring within a source string and returns the first occurrence of the substring to the end of the source string.

The search is case sensitive and takes as arguments a source string and a substring.

If the substring is not found the function returns false.

The stristr() function does exactly the same except the search is not case sensitive.

Example of strstr() and stristr()
<?php
    $sentence = "Handsome is as handsome does.";

    // This prints out handsome does.
    echo (strstr ($sentence, "handsome"));

    // This prints out Handsome is as handsome does.
    echo (stristr ($sentence, "handsome"));
?>


The strrchr() function performs a similar job as the last two functions but differs in two ways.



Examples of strrchr()
<?php
    $sentence = "Handsome is as handsome does.";

    // This prints out does.
    echo (strrchr ($sentence, "done"));

    // This prints out andsome does.
    echo (strrchr ($sentence, "and"));
?>


Extracting Values from a String

This requires a knowledge of arrays, which is covered in the tutorial Arrays.

PHP provides two functions for converting strings into arrays and arrays into strings - explode() and implode()

The explode() Function

The explode() function takes a source string and returns an array of strings formed by breaking the source string at each occurrence of a delimiter string.

The function takes as arguments a delimiter string and a source string.

It also accepts an optional limit argument that determines the maximum number of elements in the returned array. When the limit is reached then the last element in the array holds whatever is left of the subject string.

Example of explode()
<?php
    $names = "Tom Dick Harry Fred George";

    // This creates an array with each name as an element.
    $names_array = explode (" ", $names);
?>


The implode() Function

The implode() function is the opposite of the explode() function. It takes an array and returns a single string formed by joining each element in the array with a glue string between each element.

The function takes as arguments a glue string and an array.

Example of implode()
<?php
    $names = array("Tom", "Dick", "Harry", "Fred", "George");

    $name_string = implode (", ", $names);

    // This prints out Tom, Dick, Harry, Fred, George.
    echo($name_string);
?>


Previous - strings Previous - Strings     Next - Replacing Substrings Next - replacing substrings


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsPHP strings and substringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsArraysArray FunctionsSorting ArraysUser-Defined FunctionsInclude and RequireUploading FilesFile FunctionsSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook
Tips and TricksPage TemplatesForm Reply ScriptsForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.