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
https://forums.phpfreaks.com/topic/35321-stop-my-simple-reg-exp-mistake/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.