Re: greedy preg
| From: | CPT John W. Holmes | Date: | Thu, 07 Aug 2003 19:05:43 +0000 |
| Subject: | Re: greedy preg | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-158716@lists.php.net to get a copy of this message | ||
From: "skate" <root@fatcuban.com>
> $contents = preg_replace( "|<item>.*?".$file.".*?</item>|si",
> "",
> $contents );
>
> okay, so i figured out that it's matching the first occurence of <item>
> which will always be the first record and then going on to match the $file
> and deleting everything between. obviously not what i want.
>
> without giving <item> a unique attribute and without preg_match_all and
> looping through them all, is there any other way to do this? make it find
> the first occurence of <item> previous to $file, rather than from the
start?
>
> i hope this makes sense, and is a little clearer than i've been so far...
This example works... adapt to your needs. (Sorry for the delay)
<?php
$xml = "
<item>
<name>John</name>
<file>file1.xml</file>
<x>Foobar</x>
</item>
<item>
<name>Bob</name>
<file>file2.xml</file>
<x>Something</x>
</item>
<item>
<name>George</name>
<file>file3.xml</file>
<x>Gotcha</x>
</item>
";
$file = 'file2.xml';
function callback($matches)
{
global $file;
if(strpos($matches[1],$file) === FALSE)
{ return $matches[0]; }
else
{ return ''; }
}
$new_xml =
preg_replace_callback('|<item>(.*)</item>|Usi','callback',$xml);
echo nl2br(htmlentities($xml));
echo "<hr>";
echo nl2br(htmlentities($new_xml));
?>
---John Holmes...