note 102285 modified in regexp.reference.conditional by danbrown
| From: | danbrown@php.net | Date: | Mon, 07 Feb 2011 14:04:56 +0000 |
| Subject: | note 102285 modified in regexp.reference.conditional by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176728@lists.php.net to get a copy of this message | ||
Repetition of a subpattern will repeat conditionals that are contained inside it, updating
subpattern matches with iteration.
Consider the following code, which scans thru HTML, keeping track of angle brackets "<"
">". If open bracket "<" matches, then closing bracket ">"
must follow before repetition can possibly end. That way regex will effectively match only outside
of tags.
<?php
$pattern='%(*ANY)(.*?(<)(?(2).*?>)(.*?))*?\'\'%s';
$replace='\1Fred';
$subject=
'<html><body class=\'\'>\'\' went to '\'\meyer and
ran
into <b>\'\'</b>.
</body></html>'
echo
preg_replace("%(*ANY)(.*?((<)(?(3).*?>).*?)*?)\'\'%s",'\1Fred',$subject);
?>
Output will be:
'<html><body class=\'\'>Fred went to Fredmeyer and ran
into <b>Fred</b>.
</body></html>'
--was--
Repetition of a subpattern will repeat conditionals that are contained inside it, updating
subpattern matches with iteration.
Consider the following code, which scans thru HTML, keeping track of angle brackets "<"
">". If open bracket "<" matches, then closing bracket ">"
must follow before repetition can possibly end. That way regex will effectively match only outside
of tags.
<?php
$pattern='%(*ANY)(.*?(<)(?(2).*?>)(.*?))*?\'\'%s';
$replace='\1Fred';
$subject=
'<html><body class=\'\'>\'\' went to '\'\meyer and
ran
into <b>\'\'</b>.
</body></html>'
echo preg_replace($pattern,$replace,$subject);
?>
Output will be:
'<html><body class=\'\'>Fred went to Fredmeyer and ran
into <b>Fred</b>.
</body></html>'
http://php.net/manual/en/regexp.reference.conditional.php