Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1
<?php
$string = "This is the best test in the west";
$result = preg_match_all("/[A-Za-z]est/", $string, $matches);
var_dump($matches);
?>

It outputs the following:


Click here to view code image
array(1) {
[0]=>
array(3) {
[0]=>
string(4) "best"
[1]=>
string(4) "test"
[2]=>
string(4) "west"
}
}


Notice that the $matches array is actually multidimensional in that it
contains one element, which itself is an array containing all the matches to the
regular expression. This is because the expression has no subexpressions,
meaning no independent matches using parentheses. If you had
subexpressions, each would have its own element in the $matches array,
containing its own array of matches.


Moving on, preg_replace() is used to change all substrings that match a
regular expression into something else. The basic manner of using this is quite
easy: You search for something with a regular expression and provide a
replacement for it. However, a more useful variant is back referencing, using
the match as part of the replacement. For the sake of this example, say that
you have written a tutorial on PHP but want to process the text so each
reference to a function is followed by a link to the PHP manual.


PHP manual page URLs take the form www.php.net/ (for
example, www.php.net/preg_replace). The string you need to match is a
function name, which is a string of alphabetic characters, potentially also
mixed with numbers and underscores and terminated with parentheses, ().
As a replacement, you can use the match you found, surrounded in HTML
emphasis tags (), and then a link to the relevant PHP manual
page. Here is how all this looks in code:


Click here to view code image
<?php
$regex = "/([A-Za-z0-9_]*)()/";

Free download pdf