【メモ】よく使う正規表現

1.URLの自動リンク。

  1. $text = ereg_replace("[^=\"](https?|ftp)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)", "<a href=\"\\1\\2\" target=\"_blank\">\\1\\2</a>", $text);
$text = ereg_replace("[^=\"](https?|ftp)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)", "<a href=\"\\1\\2\" target=\"_blank\">\\1\\2</a>", $text);

※()でくくられたものは、その順番に「\\1」「\\2」と後述することができる。この場合では、(https?|ftp)が「\\1」、(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)が「\\2」。

2.URLの自動リンク(※短縮表示)

  1. $uri_p = "/[^=\"](https?|ftp)(:\/\/[[:alnum:]\+\$\;\?\.%,!#~*\/:@&=_-]+)/ei";
  2. $uri_r = "'<a href=\"\\1\\2\" title=\"\\1\\2\" target=\"_blank\">\\1'.substr('\\2' ,0 ,15).'...</a>'";
  3. $text = g_replace($uri_p, $uri_r, $text);
$uri_p = "/[^=\"](https?|ftp)(:\/\/[[:alnum:]\+\$\;\?\.%,!#~*\/:@&=_-]+)/ei";
$uri_r = "'<a href=\"\\1\\2\" title=\"\\1\\2\" target=\"_blank\">\\1'.substr('\\2' ,0 ,15).'...</a>'";
$text = g_replace($uri_p, $uri_r, $text);

※「g_replace」では上記「$uri_p」「 $uri_r」のように変数を使うことが可能。
※「substr(‘\\2′ ,0 ,15)」は「’\\2′を15文字で短縮表示する」という意味です。

3.$textの中から、【】で囲まれた文章を、ブロック単位で、$wordという配列に格納して抽出する。

  1. g_match_all('/【.*】/i', $text, $word);
g_match_all('/【.*】/i', $text, $word);

※iをつけないと行単位(改行ごと)に抽出される
※「.*」は、それ以降の全ての文字列。
※「if」や「foreach」などと組み合わせて使用しました。

4.$textの中から、「正規表現」を、「備忘メモ」に置換する。
(1.正規表現を使わない置換)

  1. $text = str_replace('正規表現', '備忘メモ', $text);
$text = str_replace('正規表現', '備忘メモ', $text);

※正規表現を使わない置換なので、より早く処理されるらしいです。

5.$textの中から、「正規」あるいは「表現」を、削除する。
(2.正規表現を使う置換)

  1. $text = ereg_replace('正規|表現', '', $text);
$text = ereg_replace('正規|表現', '', $text);

※|を使うとor。

6.$textの中から、「*****」で始まる文章(※行単位)を抽出し、

に囲まれた文章に置換する。
(3.正規表現を行単位で使う置換1)

  1. $text = g_replace('/\*{5}(.*)/', '
  2. <h5>\\1</h5>
  3.  
  4. ', $text);
$text = g_replace('/\*{5}(.*)/', '
<h5>\\1</h5>

', $text);

※「/」と「/」で囲むと行単位で抽出。
※「{5}」は、直前の文字を5回繰り返して出力。この場合は「*」を5回で「*****」となる。

7.$textの中から、行頭に「+」がついた文章(※行単位)を抽出し、

に囲まれた文章に置換する。
(4.正規表現を行単位で使う置換2)

  1. $text = g_replace('/\n\+(.*)/', '
  2. <ol>
  3. <li>\\1</li>
  4. </ol>
  5.  
  6. ', $text);
$text = g_replace('/\n\+(.*)/', '
<ol>
<li>\\1</li>
</ol>

', $text);

※「\n」は改行。