[英]Parsing CSS files using RegEX
我正在弄亂CSS文件,並且試圖使用PHP遍歷CSS文件。 我正在尋找的是使用正則表達式(您知道的任何更快的方法)來捕獲url()選擇器中的任何圖像路徑。
到目前為止,我能夠找到此表達式:url(([[^)] +))
但是那不是我要找的100%。 我需要一個表達式,該表達式可找到url選擇器並捕獲其中的任何內容,這意味着如果代碼中包含引號或單引號,則將不會捕獲它們。 例如:url(“ images / sunflower.png”)捕獲的字符串只能是:images / sunflower.png
感謝幫助。
請不要重新發明輪子,那樣可以避免...
Internet上有許多免費的CSS解析器。 如果您想知道它是如何完成的,請打開其中一個開源軟件,然后看看它是如何完成的。 這是一個花了2分鍾才能找到的示例:
https://github.com/sabberworm/PHP-CSS-Parser#value
我已將您指向實際顯示如何也提取URL的部分。
試試這個尺寸。 它不適用於以url(
開頭)的字符串,但是如果要解析實際的CSS,則沒有選擇器或屬性就無法啟動。
$data =' #foo { background: url("hello.jpg"); } #bar { background: url("flowers/iris.png"); }';
$output = array();
foreach(explode("url(", $data) as $i => $a) { // Split string into array of substrings at boundaries of "url(" and loop through it
if ($i) {
$a = explode(")", $a); // Split substring into array at boundaries of ")"
$url = trim(str_replace(array('"',"'"), "", $a[0])); // Remove " and ' characters
array_push($output, $url);
}
}
print_r($output);
輸出:
Array ( [0] => hello.jpg [1] => flowers/iris.png )
雖然我同意bPratik的回答,但您可能需要做的只是:
preg_match('/url\([\'"]?([^)]+?)[\'"]?\)/', 'url("images/sunflower.png")', $matches);
/**
url\( matches the url and open bracket
[\'"]+? matches a quote if there is one
([^]+?) matches the contents non-greedy (so the next closing quote wont get stolen)
[\'"]? matches the last quote
) matches the end.
*/
var_dump($matches);
array(2) {
[0]=>
string(27) "url("images/sunflower.png")"
[1]=>
string(20) "images/sunflower.png"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.