Posted By

MMDeveloper on 04/07/09


Tagged

php regexp regular Expression


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

vali29


semi-live regexp previewer


 / Published in: PHP
 

input your regexp expression and submit it. It will return the supplied text with the matched results highlighted. A sample regex pattern to submit would be:

[aqtrew] which would highlight all instances of the letters a,q,t,r,e, and w

[^a-zA-Z 0-9] which would highlight all the punctuation.

Essentially you are inputting everything between the //'s for your match.

  1. <?php
  2. class regExpTest {
  3. public $pattern = "";
  4. public $text = "";
  5. public $result = "";
  6.  
  7. public function __construct($request) {
  8. $this->pattern = "/(" . $request["regExp"] . ")/";
  9. $this->text = $request["text"];
  10. $this->highlightMatches();
  11. }
  12.  
  13. private function highlightMatches() {
  14. $this->result = preg_replace($this->pattern, '<span class="highlight">$1</span>', $this->text);
  15. }
  16. }
  17.  
  18. if ($_POST["text"] == "") {
  19. $text = "The quick brown fox, jumped over the lazy dog. Then it drank a 'foty', slapped a hoe, and went to sleep.\n\nIt's a sad story really, I mean, what did that hoe do to deserve such treatment? Who cares right?!";
  20. }
  21. else {
  22. $text = $_POST["text"];
  23. }
  24.  
  25. $pattern = $_POST["regExp"];
  26.  
  27. if ($_SERVER["REQUEST_METHOD"] == "POST") {
  28. $regExpTest = new regExpTest($_POST);
  29. $result = $regExpTest->result;
  30. } else {}
  31. ?>
  32.  
  33. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  34. <html xmlns="http://www.w3.org/1999/xhtml">
  35. <head>
  36. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  37. <title>Reg Exp Tester</title>
  38. <style type="text/css">
  39. <!--
  40.  
  41. .highlight {
  42. background-color: #66FFFF;
  43. }
  44. -->
  45. </style>
  46. </head>
  47.  
  48. <body>
  49. <form method="post" action="regExpTest.php">
  50. <table border="0" cellpadding="5" cellspacing="0">
  51. <tr>
  52. <td width="70" align="left" valign="top">Pattern:</td>
  53. <td align="left" valign="top"><input name="regExp" type="text" id="regExp" size="80" maxlength="100" value="<?php echo $pattern; ?>" /></td>
  54. </tr>
  55. <tr>
  56. <td align="left" valign="top">&nbsp;</td>
  57. <td align="left" valign="top"><label>
  58. <input type="submit" id="button" value="Submit" />
  59. </label></td>
  60. </tr>
  61. <tr>
  62. <td align="left" valign="top">Text:</td>
  63. <td align="left" valign="top"><textarea name="text" id="text" cols="45" rows="10"><?php echo $text; ?></textarea></td>
  64. </tr>
  65. </table>
  66. </form>
  67. <p><?php echo nl2br($result); ?></p>
  68. </body>
  69. </html>

Report this snippet  

You need to login to post a comment.