function | description |
---|---|
preg_match(regex, string)
|
returns true if string matches regex
|
preg_replace(regex, replacement, string)
|
returns a new string with all substrings that match regex replaced by replacement |
preg_split(regex, string)
|
returns an array of strings from given string broken apart using given regex as delimiter (like explode but more powerful)
|
The code for images.php
displays all
JPG images
in the images/
folder.
Modify it using regular expressions so that it will display only image file namess that match each of the following patterns:
(sample solution)
<?php $folder = "images"; $images = glob("$folder/*.jpg"); $regex = "/abbath/i"; // contain "abbath", case insensitive foreach ($images as $image) { if (preg_match($regex, $image)) { ?> <img src="<?= $image ?>" alt="an awesome picture" /> <?php } } // begin with "abbath" and end with "cat", "dog", or "sheep" // $regex = "/^$folder\/abbath(.*)(dog|cat|sheep).jpg$/"; // $regex = "/[0-9].jpg$/"; // end in a number // $regex = "/^[ab]{4}/i"; // start with 4 As/Bs ?>