Re: Regex help please
| From: | haliphax | Date: | Fri, 27 Mar 2009 14:58:33 +0000 |
| Subject: | Re: Regex help please | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-290759@lists.php.net to get a copy of this message | ||
On Fri, Mar 27, 2009 at 9:40 AM, Shawn McKenzie <nospam@mckenzies.net> wrote:
> I'm normally OK with regex, especially if I fiddle with it long enough,
> however I have fiddled with this one so long that I'm either totally
> missing it or it's something simple. Does it have anything to do with
> the backref, or the fact that the value of the backref has a $? I have:
>
> $out = '
> {$sites}
> <tr>
> <td>
> {Site.id}
> </td>
> </tr>
> {/$sites}';
>
> And I want to capture the first {$tag}, everything in between and the
> last {$/tag}. I have tried several things and here is my current regex
> that looks like it should work, but doesn't:
>
> preg_match_all('|{\$([^}]+)}(.+)({/\1})|Us', $out, $matches);
Shawn,
First thing I see--your first capture group doesn't include the $, and
so your final capture group will always fail given your current $out
(because it's looking for {/sites} instead of {/$sites}). Also, your
{} are outside of your capture group in \1, but inside in \3. Here's
what I came up with:
$out = '
{$sites}
<tr>
<td>
{Site.id}
</td>
</tr>
{/$sites}';
$matches = array();
preg_match_all('#{(\$[^}]+)}(.*?){(/\1)}#s', $out, $matches);
print_r($matches);
Produces this:
Array
(
[0] => Array
(
[0] => {$sites}
<tr>
<td>
{Site.id}
</td>
</tr>
{/$sites}
)
[1] => Array
(
[0] => $sites
)
[2] => Array
(
[0] =>
<tr>
<td>
{Site.id}
</td>
</tr>
)
[3] => Array
(
[0] => /$sites
)
)
Keep in mind, I had to view the page source in order to see the HTML
tags, but it showed me everything I expected to see.
HTH,
--
// Todd