2012-06-03 11 views
9

HTML文字列を有効なXMLタグ名に変換する正規表現関数を書くのに助けが必要です。例:それは文字列を取り、次ん:他の文字が発生した場合Regex - 有効なXMLタグにHTMLを変換する

  • アルファベットまたはアンダースコアが文字列で発生した場合、それはそれ
  • を保持し、それが出力文字列から削除されます。
  • 単語や文字の間に他の文字がある場合、その文字はアンダースコアに置き換えられます。
    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 
    

は、基本的には正規表現機能は、有効なXMLタグにHTML文字列を変換する必要があります。

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

ので、アルファの文字が前にありますかどうかを確認するために前後参照があります:

+3

あなたの質問は「私が書きたい」と言うが、それは要件のリストのように、目的の魔法の正規表現コードをドロップするために誰かを待って読み込みます。とにかくXMLタグとみなすものは明確ではなく、出力例には何も含まれていません。 – mario

+0

@ジャックマニー:それは今4000 upvotesを持っています..? Sheesh。 – mpen

+1

青い月に状況が一度だけ起こった場合、何か問題があります。ちょうどあなたのテストコードに「素早く汚れたパッチアップ」を追加するだけです! DOMの代わりにREGEXを使用する... – 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

をお試しくださいとそれ以外のアルファ/ノンアンダースコアを置き換えます。

1

私は次のことがうまくいくと考えています。

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

ないアルファベットまたは下線で一つ以上の文字にマッチする[^A-Za-z_]+正規表現の最初の部分。正規表現の最後の部分は同じですが、オプションです。 2つのブラックリストされた文字の間の任意の文字(アルファベットやアンダースコアさえ)をキャッチするために、中間部分、オプションでもある(.*)?を許可することです。

関連する問題