php
  • regex
  • 2012-12-11 28 views 0 likes 
    0

    我想用這個「iwdnowfreedom_body_style_var」在變量的名稱屬性中替換這個「iwdnowfreedom [body_style] [var]」。可能有幾個數組鍵,但對於我的情況,將它們刪除不應該導致任何問題。使用正則表達式替換名稱元素

    這裏是我到目前爲止的代碼:

    $pattern = '/name\\s*=\\s*["\'](.*?)["\']/i'; 
    $replacement = 'name="$2"'; 
    $fixedOutput = preg_replace($pattern, $replacement, $input); 
    
    return $fixedOutput; 
    

    我怎樣才能解決這個問題才能正常工作?

    +0

    你能給你想從和更換什麼的例子嗎? – TwiNight

    +0

    爲什麼不直接在[和]上執行str_replace?最後一次發生可能被忽略... – RonaldBarzell

    +0

    您的示例代碼doesn; t似乎與您的文本描述相關。我的文本描述中根本沒有看到「名稱」,但是您使用它的isnyou代碼模式。 –

    回答

    1

    你可以嘗試使用內建在str_replace函數功能來實現你在找什麼(假設沒有嵌套bracked如「測試[測試[關鍵]」):

    $str = "iwdnowfreedom[body_style][var]"; 
    echo trim(str_replace(array("][", "[", "]"), "_", $str), "_"); 
    

    ,或者如果你喜歡正則表達式(嵌套括號做工精細用此方法):

    $input = "iwdnowfreedom[body_style][var]"; 
    $pattern = '/(\[+\]+|\]+\[+|\[+|\]+)/i'; 
    $replacement = '_'; 
    $fixedOutput = trim(preg_replace($pattern, $replacement, $input), "_"); 
    
    echo $fixedOutput; 
    

    我想你也意味着你可能有一個字符串,如

    <input id="blah" name="test[hello]" /> 
    

    和解析name屬性,你可以只是做:

    function parseNameAttribute($str) 
    { 
        $pos = strpos($str, 'name="'); 
    
        if ($pos !== false) 
        { 
         $pos += 6; // move 6 characters forward to remove the 'name="' part 
    
         $endPos = strpos($str, '"', $pos); // find the next quote after the name=" 
    
         if ($endPos !== false) 
         { 
          $name = substr($str, $pos, $endPos - $pos); // cut between name=" and the following " 
    
          return trim(preg_replace('/(\[+\]+|\]+\[+|\[+|\]+)/i', '_', $name), '_'); 
         } 
        } 
    
        return ""; 
    } 
    

    OR

    function parseNameAttribute($str) 
    { 
        if (preg_match('/name="(.+?)"/', $str, $matches)) 
        { 
         return trim(preg_replace('/(\[+\]+|\]+\[+|\[+|\]+)/i', '_', $matches[1]), '_'); 
        } 
    
        return ""; 
    } 
    
    +0

    我們如何確保它能檢查它只替換HTMl名稱標籤內的字符串?字符串不一定是iwdnowfreedom [body_style] [var],因此必須確保它適用於name =「」 – spyke01

    +0

    內的任何內容。只需創建一些可清理字符串的html助手函數。因此,像「removeBrackets($ nameStr)」,然後當你輸出的名稱,你運行$ nameStr通過你的函數 – Supericy

    +0

    不能這樣做,因爲它是從一個wordpress主題功能,所以必須在事實或永久替換它修改10個不同的功能(大約800行) – spyke01

    相關問題