RegEx Patterns Collection
« Incomplete Page »
Why does this author post incomplete pages?
A collection of Regular Expression Patterns. The code library will not be limited to one particular programming language. Most likely, the GREP style, and PERL style of RegEx operators and special characters will be used to represent the possibilities of PHP and JavaScript.
- PHP RegEx Functions
-
- preg_replace
- Patterns for
preg_replace- Remove Extra Spaces
<?php
$str = 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>- Extract URL Data
-
Depending upon what it is you need to do with any URL, the following bit of code my help you to get started in understanding how to use the most basic Perl type (preg_replace) RegExp in your own programming.
The code to follow is a section straight from the header of a PHP file I use to read the directory contents of several localhost directories. Simple modification of the RegEx string will yeild quite different results, so if you wish to get a feel for what’s goign on here, begin by finding the pattern in the RegEx (you’ll recognize a repeating pattern, each ending in the “zero or one” operator), then add one more of the pattern to the string, or remove one of the existing patterns, and see what are your results.
For such a test, i recommend a very simple PHP file. The HTML you find at the W3C’s example basic HTML template will do fine for the HTML, and just insert this PHP at the head, before the < DOCTYPE >, and the brief
PHP echooutput in the HTML body:1____<?php 2____$process = $_SERVER['PHP_SELF']; 3____$patharray = pathinfo($process); 4____ 5____/* -------------------------------- PROCESS CURRENT DIR INFO ----- */ 6____// #00 7____$thisdir_underscortrim = str_replace("_", " ", $patharray['dirname']); 8____$curWorkDir = getcwd(); 9____ 10____/* ------------------------------- MAKE CURRENT DIR FOR READING --- */ 11____// #01 12____// REGULAR EXPRESSIONS HERE 13____// AFFECT THE PATHINFO: 14____$subject = $patharray['dirname']; 15____$replace = ''; 16____ 17____// NOTE: ADDING A FORWARD SLASH '/' LIKE SO, [/] TO THE 18____// REGEX WHICH FOLLOWS WILL FLIP-FLOP THE RESULTS 19____// DEPENDING UPON HOW DEEP THE DIRECTORY STRUCTURE AND 20____// THE NEEDS OF THE OUTPUT INFO WILL DETERMINE 21____// WHETHER TO PERFORM THIS MODIFICATION OR NOT 22____// #01 23____$removeThis = "@^([w]*|[d]*)+[/]?([w]*|[d]*)+[/]?@"; 24____$pathFound = preg_replace($removeThis, $replace, $subject); 25____ 26____// #01 27____// WORKING IN NEW SITE OR DIRECTORY? 28____// THEN UNCOMMENT NEXT LINE: 29____echo "<br /><h1 style=\"background:#FFF;color:blue;\">\$pathFound: ".$pathFound."</h1>"; 30____ 31____// #01 32____$pathNew = str_replace($pathFound, '', $subject); 33____// WORKING IN NEW SITE OR DIRECTORY? 34____// THEN UNCOMMENT NEXT LINE: 35____echo "<br /><h1 style=\"background:#FFF;color:blue;\">\$pathNew: ".$pathNew."</h1>"; 36____ 37____// #01 38____$currentDir = $pathFound;