Regular Expressions

Syntax

Not Multiple Words

mountain (?!cat|lion|cougar) will find "mountain mouse", but not "mountain cat", "mountain lion", or "mountain cougar",

Usage in PHP

I have been using the PERL RegEx library.

The example below will search HTML code looking for file paths and replacing them with a constant. For example,

<link href="/css/main.css" rel="stylesheet" type="text/css"><img src='img/utensils.jpg' width="473" height="473" border="0" usemap="#utensils" class="pushLeft"> <img width="473" height="473" border="0" src='img/utensils.jpg' usemap="#utensils" class="pushLeft"> <img src="hmg/utensils.jpg" width="473" height="473" border="0" usemap="#utensils" class="pushLeft"><link href="../myStuff.css"><img src='utensils.jpg' width="473" height="473" border="0" usemap="#utensils" class="pushLeft">

will get replaced with:

<link href="courses/uploads/main.css" rel="stylesheet" type="text/css"><img src='courses/uploads/utensils.jpg' width="473" height="473" border="0" usemap="#utensils" class="pushLeft"> <img width="473" height="473" border="0" src='courses/uploads/utensils.jpg' usemap="#utensils" class="pushLeft"> <img src="courses/uploads/utensils.jpg" width="473" height="473" border="0" usemap="#utensils" class="pushLeft"><link href="courses/uploads/myStuff.css"><img src='courses/uploads/utensils.jpg' width="473" height="473" border="0" usemap="#utensils" class="pushLeft">

Additionally, it is only going to process paths that follows src=' or link href=' (double quotes are fine too).

<?php
	$pattern = '#((link href)|(\ssrc))=([\'"])(?!http|//)(.*?)(\w+\.[\w\.]+)([\'"])(.*?)>#';
	$replacement = '$1=$4courses/uploads/$6$7$8>';
	$main = preg_replace($pattern, $replacement, $main);
?>

When using RegEx in PHP there are a few syntactical issues to be aware of.