簡體   English   中英

PHP使用正則表達式更改HTML字符串中的CSS屬性

[英]PHP Using Regular Expressions to change css propertyin html string

我下面有html,例如,我想使用正則表達式即時更改字體大小。

<p><span style="font-size: small;"><img style="float: left;padding:5px" title="Ikechukwu to host Lagos Smirnoff party" src="afrostarpics/586.jpg" alt="Ikechukwu to host Lagos Smirnoff party" width="200" height="300">Smirnoff held a party like never seen before in East, North and West Africa on Friday 23rd September 2011, when they held a “Kick off” party for the Smirnoff Midnight Cruise.&nbsp; The grand party held in the populous West African nation of Nigeria was so successful that it left revellers literally begging for more.</span></p>

這是我有的正則表達式

    <?php 
$bd=$nobj->body;//html string to change
$selector="font-size"; //selector to change
$property="1.2em"; //new value
 preg_replace('/('.$selector.'\s*\{[\w\s:\-;\(\)#]*)('.$property.'\s*:)([^;\}]+)(;|\})/Ui', '$1 $4', $bd); 
echo $bd;
?>

關於為什么這不起作用的任何想法

如果您打算為此使用正則表達式,則可能會發現此模式更有效:

$bd = preg_replace('/\b'.$selector.'\s*:[^;}"\']*/i', $selector.':'.$property, $bd);

那應該至少要在99%的時間內完成您想做的事情。

但是,我想指出的是,您似乎正在嘗試使用正則表達式來解析嵌入在HTML中的CSS,而regex通常不擅長此功能。 即使完成了這個簡單的任務,要以健壯的方式解決問題,您也必須區分HTML屬性值和其他文本,這意味着您必須(至少部分地)解析HTML。 使用正則表達式執行此操作通常不是一個好主意,但是對於jQuery (客戶端)或HTML Purifier (服務器端)而言它非常簡單。

為什么正則表達式如此危險呢? 好吧,盡管任務本身非常簡單,但是您可能事先不知道純文本部分要說什么,而regex不能分辨純文本和HTML之間的區別。 因此,如果在您的純文本中出現“ font-size:”一詞(意味着Smirnoff held a party like... ),它可能會破壞任何理智的正則表達式。 不可能? 是的,但是它仍然是潛在的錯誤。

一個可能的原因是preg_replace返回修改后的字符串,因此您必須保存並使用返回值-如果正則表達式正確,則類似的事情將起作用:

$bd = preg_replace('/('.$selector.'\s*\{[\w\s:\-;\(\)#]*)('.$property.'\s*:)([^;\}]+)(;|\})/Ui', '$1 $4', $bd);
echo $bd;

您的正則表達式對我來說看起來過於復雜。

您總是可以將結果解析為XML,然后修改屬性,但是假設您仍然想要REGEX,我認為這樣就可以滿足要求:

$old = '<p><span style="font-weight:bold;color:blue;font-size: small;"><img style="float: left;padding:5px" title="Ikechukwu to host Lagos Smirnoff party" src="afrostarpics/586.jpg" alt="Ikechukwu to host Lagos Smirnoff party" width="200" height="300">Smirnoff held a party like never seen before in East, North and West Africa on Friday 23rd September 2011, when they held a “Kick off” party for the Smirnoff Midnight Cruise.&nbsp; The grand party held in the populous West African nation of Nigeria was so successful that it left revellers literally begging for more.</span></p>';
$selector      = 'font-size';
$desired_value = '1\.2em';
$new = preg_replace(
    '/\b(' . $selector . ')\s*:\s*(?!' . $desired_value . ').+\s*([;"\'])/Ui',
    '\1:' . stripslashes($desired_value) . '\2',
    $old
);

作為參考,使用您提供的值,可以得到以下輸出正則表達式:

\b(font-size)\s*:\s*(?!1\.2em).+?\s*([;"'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM