Wedge

Public area => The Pub => Off-topic => Topic started by: PantsManUK on March 12th, 2012, 02:51 PM

Title: Let me hold a dollar?
Post 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?
Title: Re: Let me hold a dollar?
Post by: Arantor on March 12th, 2012, 03:08 PM
Gut instinct says where $str holds the current content...

Code: [Select]
$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. ;)
Title: Re: Let me hold a dollar?
Post by: PantsManUK on March 12th, 2012, 03:14 PM
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:-

Code: [Select]
$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.
Title: Re: Let me hold a dollar?
Post by: Nao on March 12th, 2012, 11:45 PM
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.

:)
Title: Re: Let me hold a dollar?
Post by: Arantor on March 12th, 2012, 11:47 PM
Quote
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.