12 Mar, 2003
PHP Command Prompt Part II – Regular Expressions
Posted by: dave In: Admin-type scripts
How often has it happened that you have a few hundred pages, with something that needs to be changed on each page? Luckily, PHP >= 4.2.0 ships with PCRE enabled by default, opening up the power of regular expressions to PHP scripters.
I'm not going to give a primer on REs (Regular Expressions), but if you don't know about them you should really sit right down & teach yourself. O'Reilly has an excellent book on them, and the program Visual REGEXP (search Freshmeat) is a great learning tool.
If you need help on running PHP from the command prompt, see my earlier post on the topic.
Here's the setup:
The situation:
I have 100 old web pages where I want to replace all the font tags with a standard one. (Yes, this is why you should use CSS) This is a bit simplified, but you should easily be able to extend this script to replace only the "face" attribute for example.
The Script:
$dirpath="/usr/wget/dev/";
$pattern="/<\s*font[^>]*>/";
$replace="<font face=\"Verdana\" size=\"2\"&glt";
if ($handle = opendir($dirpath)) {
while (false !== ($file = readdir($handle))) {
if (is_file($file) && fnmatch("*html", $file)) {
$lines = file($file);
foreach ($lines as $line_num => $lines ) {
echo "$file\n";
echo "Old:$lines\n";
$lines=preg_replace($pattern, $replace, $lines);
echo "New:$lines\n";
}
}
}
closedir($handle);
}
The important lines are $pattern, $replace & the preg_replace function. I've left out writing it back to a file to save space.
$pattern is a RE matching all tags with "font" in them, and grabbing the entire tag.
$replace is obviously what I want to replace the old font tags with.
The preg_replace function does all the work, matching the pattern to the string $lines & if its a match, replacing with $replace. If there is no match, no replacement is made.
Again, you can easily leverage your knowledge of PHP to write some simple administrative scripts to make your life easier…
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
scriptygoddess
