preg replace: replacing html tags with inline css style

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

preg replace: replacing html tags with inline css style

Post by lauthiamkok »

Hi,

I am not sure if this is possible...

suppose I have these paragraphs, <p> tags, and links, <a> tags,

<p>this is a sample paragraph 1.</p>
<p>this is a sample paragraph 2.</p>
<p>this is a sample paragraph 3 with a <a href="www.link.com">link 1</a></p>
<p>this is a sample paragraph 4 with a <a href="www.link.com">link 2</a></p>

and I want to embed the css style into these tags when you submit it, so it will output:

<p style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color: #000000; ">this is a sample paragraph 1.</p>
<p style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color: #000000; ">this is a sample paragraph 2.</p>
<p style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color: #000000; ">this is a sample paragraph 3 with a <a href="www.link.com" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; color: #000000; ">link</a></p>

so I think I could use preg_replace(),

preg_replace("/<p\/>/si", "/<p style=\"font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color: #000000;\"\/>/si", $content);
preg_replace("/<a\/>/si", "/<a style=\"font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; color: #000000;\"\/>/si", $content);

but I think my expressions are incorrect especially in the <a> tags bcos I have the url in them...

thanks so much if u have any ideas...

Many thanks!
Lau
User avatar
mecha_godzilla
Forum Contributor
Posts: 375
Joined: Wed Apr 14, 2010 4:45 pm
Location: UK

Re: preg replace: replacing html tags with inline css style

Post by mecha_godzilla »

Have a look at the example on this page:

http://uk2.php.net/manual/en/function.p ... .php#87944

Although this code is being used to convert BBCode into HTML tags, the important thing to notice is that it's preserving the tag's attributes as well as any other content contained within the tags.

HTH,

Mecha Godzilla
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: preg replace: replacing html tags with inline css style

Post by requinix »

Put the CSS rules in a stylesheet or <style>. There's no reason you should need to put them inline.
Post Reply