2012-06-03 70 views
9

我需要幫助編寫一個正則表達式函數,將HTML字符串轉換爲有效的XML標記名稱。例如:它需要一個字符串,並執行以下操作:正則表達式 - 將HTML轉換爲有效的XML標記

  • 如果一個字母或下劃線的字符串時,它如果出現任何其他字符保留它
  • ,它是從輸出字符串中刪除。
  • 如果在單詞或字母之間出現任何其他字符,則將其替換爲Underscore。
Ex: 
Input: Date Created 
Ouput: Date_Created 

Input: Date<br/>Created 
Output: Date_Created 

Input: Date\nCreated 
Output: Date_Created 

Input: Date 1 2 3 Created 
Output: Date_Created 

基本上正則表達式的功能應該在HTML字符串轉換爲有效的XML標籤。

+3

你的問題說:「我要寫」,但它讀起來就像一個要求列表和等待有人砸所需魔術正則表達式代碼。不清楚你認爲XML標籤是什麼,輸出示例不包含任何內容。 – mario

+0

@JackManey:現在有超過4000個upvotes ..?嘖。 – mpen

+1

如果情況在藍色月亮中只出現一次,那麼這就是錯誤,只是在旋轉的測試代碼中添加一個「快速和髒的修補程序」!並使用REGEX INSTEAD DOM ... – Cylian

回答

5

正則表達式的一點,一點的標準功能:

function mystrip($s) 
{ 
     // add spaces around angle brackets to separate tag-like parts 
     // e.g. "<br />" becomes " <br /> " 
     // then let strip_tags take care of removing html tags 
     $s = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $s)); 

     // any sequence of characters that are not alphabet or underscore 
     // gets replaced by a single underscore 
     return preg_replace('/[^a-z_]+/i', '_', $s); 
} 
2

試試這個

$result = preg_replace('/([\d\s]|<[^<>]+>)/', '_', $subject); 

說明

" 
(    # Match the regular expression below and capture its match into backreference number 1 
        # Match either the regular expression below (attempting the next alternative only if this one fails) 
     [\d\s]   # Match a single character present in the list below 
         # A single digit 0..9 
         # A whitespace character (spaces, tabs, and line breaks) 
    |    # Or match regular expression number 2 below (the entire group fails if this one fails to match) 
     <    # Match the character 「<」 literally 
     [^<>]   # Match a single character NOT present in the list 「<>」 
     +    # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
     >    # Match the character 「>」 literally 
) 
" 
2

應該能夠使用:

$text = preg_replace('/(?<=[a-zA-Z])[^a-zA-Z_]+(?=[a-zA-Z])/', '_', $text); 

所以,有lookarounds,看看是否有一個字母字符前和a fter,並替換它之間的任何非alpha /非下劃線。

1

我相信下面的工作。

preg_replace('/[^A-Za-z_]+(.*)?([^A-Za-z_]+)?/', '_', $string); 

[^A-Za-z_]+匹配一個或多個字符不是字母或下劃線的正則表達式的第一部分。正則表達式的結尾部分是相同的,除了它是可選的。這是爲了允許中間部分(.*)?也是可選的,以捕獲兩個黑名單字符之間的任何字符(甚至是字母和下劃線)。

相關問題