note 51739 added to reference.pcre.pattern.modifiers
| From: | csaba at alum dot mit dot edu | Date: | Sat, 09 Apr 2005 00:40:35 +0000 |
| Subject: | note 51739 added to reference.pcre.pattern.modifiers | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-87745@lists.php.net to get a copy of this message | ||
Extracting lines of text:
You might want to grab a line of text within a multiline piece of text. For example, suppose you
want to replace the first and last lines within the <body> portion of a web $page with your
own $lineFirst and $lineLast. Here's one possible way:
<?php
$lineFirst = "This is a new first line<br>\r\n";
$lineLast = "This is a new last line<br>\r\n";
$page = <<<EOD
<html><head>
<title>This is a test page</title>
</head><body>
This is the first line<br>
Hi Fred<br>
Hi Bill<br>
This is the last line<br>
</body>
</html>
EOD;
$re = "/<body>.*^(.+)(^.*?^)(.+)(^<\\/body>.*?)/smU";
if (preg_match($re, $page, $aMatch, PREG_OFFSET_CAPTURE))
$newPage = substr($text, 0, $aMatch[1][1]) .
$lineFirst . $aMatch[2][0] .
$lineLast . $aMatch[4][0];
print $newPage;
?>
The two (.+) are supposed to match the first and last lines within the <body> tag. The /s
option (dot all) is needed so the .* can also match newlines. The /m option (multiline) is needed
so that the ^ can match newlines. The /U option (ungreedy) is needed so that the .* and .+ will
only gobble up the minimum number of characters necessary to get to the character following the * or
+. The exception to this, however, is that the .*? temporarily overrides the /U setting on .*
turning it from non greedy to greedy. In the middle, this ensures that all the lines except the
first and last (within the <body> tag) are put into $aMatch[2]. At the end, it ensures that
all the remaining characters in the string are gobbled up, which could also have been achieved by
.*)\\z/ instead of .*?)/
Csaba Gabor from Vienna
----
Manual Page -- http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+51739
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51739&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51739&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51739&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51739&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51739&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+51739&report=yes
Search -- http://master.php.net/manage/user-notes.php