Pattern Basics

Let’s start with something simple: detection of a substring anywhere within a string.

<?php
// Substring detection with a basic string function
$present = (strpos($string, 'foo') !== false);

// Same with a PCRE function
$present = (preg_match('/foo/', $string) == 1);
?>

Notice that the pattern in the preg_match() call is fairly similar to the string used in the strpos() call. In the former, / is used on either side of the pattern to indicate its beginning and end. The first character in the pattern string is considered to be the pattern delimiter and can be any character you specify. When choosing what you want to use for this character (/ is the most common choice), bear in mind that you will have to escape it (covered in the Escaping section later) if you use it within the pattern. This will make more sense a little later in the chapter.

A difference between the two functions used in this example is that strpos() returns the location of the substring within the string beginning at 0 or false if the substring is not contained within the string. This requires the use of the === operator to tell the difference between the substring being matched at the beginning of the string or not at all. By contrast, preg_match() returns the number of matches it found. This will be either 0 or 1 since preg_match() stops searching once it finds a match.


© PCRE Extension — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (03.09.2014)
Views: 373 | Rating: 0.0/0
Total comments: 0
avatar