2013-02-03 30 views
1

我想轉換html文檔中的所有大小。所有與px的應該除以4.所以100px將變成25px。

例如:

<div style="height:100px;"></div> 

應該成爲

<div style="height:25px;"></div> 

這裏是一個PHP代碼我寫的。但它不起作用。

$content = "<div style=\"height:100px;\"></div>"; 
$regex = "#([0-9]*)px#"; 
$output = preg_replace($regex,"$1/4",$content); 

我該怎麼辦?

+3

使用preg_replace_callback。 – nhahtdh

回答

3

作爲替代preg_replace_callback,您可以使用e修飾符來評估替換爲PHP:

$content = "<div style=\"height:100px;\"></div>"; 
$regex = "#([0-9]*)px#e"; 
$output = preg_replace($regex,"round($1/4).'px'",$content); 
+0

結果是'

'。 'px'丟失。 – flowfree

+0

@bsdnoobz對不起,忘了在'px'中加入,修正。 –

+0

+1:使用e修飾符和內置函數圓:) – 2013-02-03 17:26:14

0
<?php 
$content = "<div style=\"height:100px;\"></div>"; 
$regex = "#([0-9]*)px#"; 

$output = preg_replace_callback($regex, 
    create_function('$matches', 
    'return ceil($matches[1]/4)."px";'), 
    $content); 
?> 

<?php 
$content = "<div style=\"height:100px;\"></div>"; 
$regex = "#([0-9]*)px#"; 
$output = preg_replace_callback($regex, 'myfunc', $content); 
function myfunc($matches){ 
return ceil($matches[1]/4).'px'; 
} 
?>