Mega Code Archive

 
Categories / Php / Content Management
 

Regex Generator

<? //read the files into arrays $expression = file('path/to/expression.txt'); $replace = file('path/to/replace.txt'); //replace via array $content = preg_replace($expression,$replace,$content); ?> /*Now you just call regex.php with an include function. You can do this where ever you like as long as your paths are correct.*/ <? $content = "string" //this is you un regexed text include('path/to/regex.php'); //this pulls in regex.php and runs $content through it echo $content; //display the newly regexed text, of course you can do whatever with it ?> /*Now you need to build the form for entering you expressions and replacements. We'll call it regexform.php, but you could really put the code anywhere, persaonly I have it in the admin pages of the blogging app I'm building. This page takes info from a form and saves it into those previously balnk .txt files*/ <? //regexform.php //if information is present process the form if ($_POST['expression'] && $_POST['replace']) { $replace = stripslashes($_POST['replace'])."\n"; $expression = stripslashes($_POST['expression']); $expression = "/".$expression."/\n"; $exp = "path/to/expression.txt"; $fh = fopen($exp,"a"); fwrite($fh,$expression); fclose($fh); $rep = "path/to//replace.txt"; $fh2 = fopen($rep,"a"); fwrite($fh2,$replace); fclose($fh2); } //print the form print "<form action=\"regexform.php\" method=\"post\">"; print "expression:<br /><input type=\"text\" name=\"expression\" size=\"30\" /><br />"; print "replacement:<br /><input type=\"text\" name=\"replace\" size=\"30\" /><br />"; print "<input type=\"submit\" name=\"submit\" value=\"enter regex\" />"; print "</form>"; ?> /*Now you can enter your expression and replacement into the form above and they are automatically added to the regex arrays. The order they come in is important to the array structure, so don't delete from one list without deleting the matching item from the other list. If you have tried to use this code and are having a problem, the usual culprits are paths. I wrote this to be used on multiple pages in a site from a remote location, and anytime you use include() you need to check not only the paths in your main page, but also any page you are includ()ing.*/