9

HTML 文字列を有効な XML タグ名に変換する正規表現関数を作成するのに助けが必要です。例: 文字列を受け取り、次のことを行います。

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

4

4 に答える 4

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);
}
于 2012-06-03T04:39:18.543 に答える
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 “&lt;” literally
      [^<>]           # Match a single character NOT present in the list “&lt;>”
         +               # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
      >               # Match the character “&gt;” literally
)
"
于 2012-06-03T04:20:34.823 に答える
2

使用できるはずです:

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

そのため、前後にアルファ文字があるかどうかを確認し、その間の非アルファ/非アンダースコアを置き換えるルックアラウンドがあります。

于 2012-06-03T04:20:57.443 に答える
1

私は以下がうまくいくはずだと信じています。

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

正規表現の最初の部分は、[^A-Za-z_]+アルファベットまたはアンダースコア以外の 1 つ以上の文字に一致します。正規表現の最後の部分は、オプションであることを除いて同じです。これは、同じくオプションである中間部分が、(.*)?ブラックリストに登録された 2 つの文字の間にある任意の文字 (アルファベットやアンダースコアも含む) をキャッチできるようにするためです。

于 2012-06-03T04:22:20.970 に答える