note 31945 added to function.preg-match
| From: | avrosmalenNOFUCKING at SPAMhotmail dot com | Date: | Fri, 09 May 2003 16:31:06 +0000 |
| Subject: | note 31945 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-47749@lists.php.net to get a copy of this message | ||
A comprehensive guide on (Perl) regular expressions:
[http://www.wdvl.com/Authoring/Languages/Perl/
PerlfortheWeb/pattern_matching.html]
I inserted an example below for a search & change (this time not a search & delete as shown
lots of time in the other comments).
If you want to do a search & change you can use the following example:
Say I want to search a html file and change all the direct links to point to a template file with an
added variable. The variable would be the original name of the html file (the (\w+) block). It would
look like this:
$file = "some_file.html";
$search_string = "/(<a href=")(\w+)(\.html)/i";
$replace_string = "\${1}template_file.php?pagename=\$2";
$contents = file($file);
foreach ($contents as $line_num => $line) {
if (preg_match('/(<a href=")(\w+)(\.html)/i', $line)) {
echo ($line_num. " before: ". $line. "<br>");
$line = preg_replace($search_string, $replace_string, $line);
echo ($line_num. " after: ". $line. "<br>");
}
}
Make sure you use double quotes in the $replace_string or the blocks $1 and $2 will not be replaced
with the original contents.
Add a piece of code that 'walks' all the html files in a directory and you could use it to
move entire (static) websites into a database in just one go.
Later,
Tone
--
http://www.php.net/manual/en/function.preg-match.php
http://master.php.net/manage/user-notes.php?action=edit+31945
http://master.php.net/manage/user-notes.php?action=delete+31945
http://master.php.net/manage/user-notes.php?action=reject+31945