You want to match a pattern found in an array instead of a search string.
Use preg_grep(). It returns an array of values that match a patetrn found in an array.
<html> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php if (isset($_POST['submit'])) { process_form(); } else { display_form();// display form for the first time } function display_form() { echo <<<HTML <form action = "$_SERVER[SCRIPT_NAME]" method="post"> Regular Expression for preg_split (include the delimiter):<br /> <input type="text" name="pattern" size="70" value="/[:,;]/m" /><br /> <br /> Regular Expression for preg_grep (include the delimiter):<br /> <input type="text" name="pattern2" size="70" value="/([a-z])\\1/i" /><br /> <br /> Text:<br /> <textarea name="text" rows="5" cols="50"> Fruits: apple, orange, banana; Vegetables: carrot, tomato, onion </textarea><br /> <input type="submit" name="submit" value="Check" /> </form> <table border> <tr bgcolor="lightcyan"> <th align="left">Regular Expression</th> <th align="left">Text</th> </tr> <tr> <td>/[,;] ?/m</td> <td>apple;banana,cantaloupe; strawberry,watermelon; pineapple, fuji apple </td> </tr> <tr bgcolor="lightyellow"> <td></td> <td> </td> </tr> </table> HTML; } function process_form() { // stripslashes and trim the strings $pattern = stripslashes(trim($_POST['pattern'])); $pattern2 = stripslashes(trim($_POST['pattern2'])); $text = trim($_POST['text']); echo "The result of finding using <br /><font color=red>$pattern2</font><br /> against<br /><font color=red>$text</font><br /> is:<br />"; // match the pattern $matches = preg_split($pattern, $text); $matches_grep = preg_grep($pattern2, $matches); echo "<br />The words containing double letters are:<br />"; foreach ($matches_grep as $key =>$values) { echo $key, " => ", $values, "<br />"; } echo "<br /><a href=\"$_SERVER[SCRIPT_NAME]\">Check again?</a>"; } ?> </p> </body> </html> |