Wedge
Public area => The Pub => Off-topic => Topic started by: PantsManUK on March 12th, 2012, 02:51 PM
-
Oh great and all powerful deities of PHP... :eheh:
I need a way to inject a little HTML text into an HTML "page" (it's an email actually, but not important) just after the opening body tag (so "<body><p>" becomes "<body>Insert text here.<p>"), but I want it to work whether the opening body tag is "<body>" or "<body class='irregardless' id='a-whole-nuther' style='all-of-a-sudden'>" or anything else in that general area. The HTML is all in a single variable, so I just need something that does a needle/haystack replace (case insensitive) in all cases.
I've successfully used str_ireplace against just "<body>" without any problems, but my preg-fu doesn't extend to catching all cases. Help?
-
Gut instinct says where $str holds the current content...
$str = preg_replace('/<body([^>]*)>/i', '<body$1>' . $new_stuff, $str);
But I'm doing that off the hoof, in between other things and I'm no regexpert. ;)
-
Thanks Pete. It's a far better start than I had managed myself. I'll pop that into my test code and fight with it until it submits to my will.
Update: It was real close and I only needed to fight with it a little bit:-
$str = preg_replace('/<body(.*?)>/is', '<body$1>' . $new_stuff, $str);
The (very minor) change came straight outta the first comment on the PCRE Pattern Syntax page on php.net [ http://uk3.php.net/manual/en/reference.pcre.pattern.syntax.php#87197 ]. Kinda wish I'd spotted it before as it would have obviated me having to ask here.
-
Technically, both your regex and Pete's do exactly the same ;)
.*? = greedy = it will stop at the first occurrence of the next character (>). Newlines are taken into account by adding the 's' modifier at the end.
[^>]* will also stop before the next >. Newlines are taken into account without a modifier, because it's a negated character class and doesn't need that.
:)
-
Technically, both your regex and Pete's do exactly the same
I figured that would be much the case, though I'd imagine the backtracking should be reduced a bit with the specific character class?
/meis not really a regex ninja.