⊗ppPmRgAT 246 of 447 menu

Automatic Testing of Regex in PHP

Let's write code that will allow us to conveniently test our written regex on multiple strings at once.

Let our regex for tests be stored in the following variable:

<?php $reg = '#\d{3,}#'; ?>

Let's create an array of strings for testing:

<?php $arr[] = 'aaa 123 bbb'; $arr[] = 'aaa 12345 bbb'; $arr[] = 'aaa 12x bbb'; $arr[] = 'aaa 12 bbb'; ?>

Let's loop through this array, checking each element with our regex:

<?php foreach ($arr as $str) { echo $str . ' ' . preg_match($reg, $str) . '<br>'; } ?>

Let's put all the code together and get a convenient template for testing regex:

<?php $reg = '#\d{3,}#'; // your regex $arr[] = 'aaa 123 bbb'; // 1 $arr[] = 'aaa 12345 bbb'; // 1 $arr[] = 'aaa 12x bbb'; // 0 $arr[] = 'aaa 12 bbb'; // 0 foreach ($arr as $str) { echo $str . ' ' . preg_match($reg, $str) . '<br>'; } ?>

Suppose you need to check that a string contains a fractional number. Using the proposed script, test your regex on various strings.

byenru