简体   繁体   中英

Adding px to top and left attibute

So I got this program that gives me a bunch of html-output with some inline styling.

It typically looks like this:

<DIV style="position:absolute;top:126;left:324"><nobr><span class="ft010"><b>2011</b></span></nobr></DIV>
<DIV style="position:absolute;top:126;left:386"><nobr><span class="ft010"><b>2010</b></span></nobr></DIV>

Now I know this is a mess, but it's what I get and changing it ain't an option right now. What I however need to do is get a regexp to input px after the top and height attributes. So what I want looks like this:

<DIV style="position:absolute;top:126px;left:324px"><nobr><span class="ft010"><b>2011</b></span></nobr></DIV>
<DIV style="position:absolute;top:126px;left:386px"><nobr><span class="ft010"><b>2010</b></span></nobr></DIV>

The html is output as one long string so I need to find all occurences of top and left and add px after the numeric value. I've been trying lots of different solutions, but still can't get it right. Would be greatful if someone could help me find the correct regexp for my issue. I'm horrible at that stuff.

$html = preg_replace('%(top|left|right|bottom)(:[0-9]{1,4})(;|")%', '$1$2px$3', $html);

This should search for any of the CSS position keywords, followed by a colon, a number (1-4 digits long), and either a double quote ( " ) or a semi-colon ( ; ).

It will then take all three of those parts (the parts within the parentheses) and stitch them back together with a px in the right place.

http://codepad.viper-7.com/UjYCV3

Have you tried this?

$html=str_replace(';left:','px;left:',$html);
$html=str_replace('"><nobr>','px"><nobr>',$html);

I think you need something like this:

$html=preg_replace('/(.+)(left|top|bottom|right):([\d]+)(.+)/i','$1$2:$3px;$4',$html);

I have not tested but I think regex is well written

比费比更合适的答案是这样的:

$html = preg_replace("/(?:left|top|right|bottom|width|height)\s*:\s*\d+/","$0px",$html);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM