2014-09-23 111 views
0

我有一段PHP代碼,它向服務器寫入一個字符串,它實際上是一個html文件,但在寫入之前,我想通過翻轉並將所有「Npx」替換爲「[N/10] REM」。因此,「寬:203px」將成爲「寬度:20.3rem」和頂部:46px」將成爲‘頂:?4.6rem’有誰看到一個正則表達式的字符串,將做到這使用正則表達式將Npx轉換爲[N/10] rem

感謝

回答

1

剛剛捕獲px之前數字然後匹配字符串px並用.$1rem 更換所有的字符凡$1是指存在於組索引內的字符1.

(\d)px 

替換字符串:

.$1rem 

DEMO

$string = <<<EOT 
width:203px 
top:46px 
top:6px 
EOT; 
$pattern = "~(\d)px~"; 
$replacement = ".$1rem"; 
echo preg_replace($pattern, $replacement, $string); 

輸出:

width:20.3rem 
top:4.6rem 
top:.6rem 
+0

美麗!謝謝。 – Steve 2014-09-23 13:11:58

+0

不客氣.. – 2014-09-23 13:13:26

+0

還有一件事。你能否解釋$ pattern值中的「〜」字符?謝謝。 – Steve 2014-09-23 15:40:01

相關問題