Posted By

sekihin on 08/11/09


Tagged

char


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


全角を半角にする


 / Published in: PHP
 

  1. // *********************************************************
  2. // 全角を半角にする
  3. // @param string $instr 変換前文字列
  4. // @return string 変換後文字列
  5. // 2008/07/30 追加 By B.Xi
  6. // *********************************************************
  7. function zen2han($instr) {
  8. $flag = FALSE; //直前文字が全角カタカナならTRUE
  9. $len = mb_strlen($instr);
  10. $ofst = 1;
  11. $outstr = '';
  12.  
  13. for ($ofst = 0; $ofst < $len; $ofst++) {
  14. $ch = mb_substr($instr, $ofst, 1);
  15. if ($ch == 'ー') {
  16. if ($flag) $outstr .= 'ー'; //カタカナの長音記号
  17. else $outstr .= $ch;
  18. } else if (mb_ereg_match('[ァ-ヶ]+', $ch)) { //カタカナの範囲
  19. $outstr .= mb_convert_kana($ch, 'k');
  20. $flag = TRUE;
  21. } else if (mb_ereg_match('[0-9]+', $ch)) { //全角数字の範囲
  22. $outstr .= mb_convert_kana($ch, 'n');
  23. $flag = TRUE;
  24. } else if (mb_ereg_match('[A-Z]+', $ch)) { //全角英字の範囲
  25. $outstr .= mb_convert_kana($ch, 'r');
  26. $flag = TRUE;
  27. } else if (mb_ereg_match('[ぁ-ん]+', $ch)) { //ひらがなの範囲
  28. $flag = TRUE;
  29. $outstr .= mb_convert_kana($ch, 'h');
  30. } else {
  31. $outstr .= $ch;
  32. $flag = FALSE;
  33. }
  34. }
  35. return $outstr;
  36. }

Report this snippet  

You need to login to post a comment.