php
  • regex
  • preg-replace
  • 2010-08-17 75 views 3 likes 
    3

    我只是不知道這一點,由於某種原因,這一點:爲什麼preg_replace會提供此輸出?

    $string = "#mainparent { 
    position: relative; 
    top: 100px; 
    left: 100px; 
    width:4994px; 
    }"; 
    
    $elementwidth = "88"; 
    
        $re1='(.*?)'; # Non-greedy match on filler 
        $re2='(mainparent)'; # Word 1 
        $re3='(.*)'; # Non-greedy match on filler 
        $re4='(width:)'; 
        $re5='(.*)'; # Word 2 
        $re6='(;)'; # Any Single Character 1 
    $pattern="/".$re1.$re2.$re3.$re4.$re5.$re6."/s"; 
        $replacement= '$1'.'$2'.'$3'. '$4'. $element_width .'$6'; 
        $return_string = preg_replace_component ($string, $pattern, $replacement); 
        #c} 
    
        echo $return_string; return; 
    

    輸出這個(如下圖),我不明白爲什麼它替換的「寬:」根據我所設置的方式它..任何建議表示讚賞

    #mainparent { position: relative; top: 100px; left: 100px; 88; } 
    
    +1

    什麼是'preg_replace_component()'?你建立的一些自定義功能? – animuson 2010-08-17 02:42:51

    +0

    有一個更好的方法來做到這一點。它被稱爲[LESS](http://lesscss.org/) – NullUserException 2010-08-17 02:44:28

    回答

    5

    的問題是,您的替換字符串看起來是這樣的:

    '$1$2$3$488$6' 
         ^^^ 
    

    由於字符n組緊隨其後棕褐色是一個數字,它被解釋爲第48組而不是第4組。

    請參閱preg_replace手冊「Example#1使用反向引用後跟數字文字」。使其工作所需的最小變化是由大括號包圍4,使其從88

    $replacement = '$1' . '$2' . '$3'. '${4}'. $element_width . '$6'; 
    

    分離但這不是做一個很好的方式,也有一些與您的代碼問題。

    • 正則表達式不適合解析和修改CSS。
    • 首先你寫$elementwidth然後你寫$element_width
    • 如果您只打算替換其中的一個,則不需要創建6個不同的組。
    +3

    更何況他用「88」而不是「88px」。此外,爲什麼這是downvoted? – animuson 2010-08-17 02:49:08

    +0

    嗨裏克,這是正確的答案。 – buley 2010-08-17 03:06:16

    +0

    它來自一個正則表達式生成器,這就是爲什麼它在6個組中,是的,我將$ element_Width名稱複製到這個帖子中時出錯,所以這不是問題...只要「88」改爲「88px」,這對此沒有影響,我只是測試了這個..爲什麼要取代'(。*)'這個問題? – Rick 2010-08-17 03:09:26

    相關問題