Jump to content

Stop my (simple) Reg Exp mistake


flash gordon

Recommended Posts

Hi
[code]
$contents = '<Template id="0" url="Templates/foo" name="Fudcake" >';
$contents .= '<fields>Hello</fields>';
$contents .= '</Template>';

$contents .= '<Template id="0" url="Templates/foo" name="Flash" >';
$contents .= '<fields>Hello</fields>';
$contents .= '</Template>';

$myVar = "Flash";
$pattern = '/<Template .+? name="' . $myVar . '"/s';
preg_match_all($pattern, $contents, $matches);
print_r($matches);
exit();

// output:
//    <Template id="0" url="Templates/foo" name="Fudcake" ><fields>Hello</fields></Template><Template id="0" url="Templates/foo" name="Flash"
[/code]

My goal and what I think it should output is simply [b][i]<Template id="0" url="Templates/foo" name="Flash"[/i][/b].

Can anyone see my error?
:)
Link to comment
Share on other sites

Initially you were not confining your regex to stay within the tag, but only to stop when it first encountered a name attribute. [tt][^>]+ [/tt]tells the pattern to match one or more characters that are not ">", thus staying within the tag. Once the engine hits the end of the tag, it backtracks attempting to satisfy the rest of the pattern ("n", then "a", then "m", then "e", and so on). If the name attribute happened to be towards the beginning of the tag--unlike your example--[tt][^>]+?[/tt] would be a better fit.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.