LoginSignup
16

More than 5 years have passed since last update.

PHP よく使う関数 まとめ

Last updated at Posted at 2016-03-07

 
■ require()
   ファイルを読み込む (読み込み時に失敗したらエラーが出て止まる)
   require_once('test.php');
   
■ include_once()
   ファイルを一度だけ読み込む (読み込みに失敗してもエラーはでるがその後の処理は続く)
   ※絶対パスの場合
   require_once realpath(dirname(FILE)).'./../test1/test2/test3.php';

■ htmlspecialchars()
   エスケープ処理(半角の<>’”&を無効にする)
   return htmlspecialchars($string,ENT_QUOTES,'UTF-8');
   
■ str_replace()
   不要なものを取り除く
   $tel = "080-6666-9999";
$henkan = str_replace("-","",$tel);//$telからハイフンを取り除く

■ preg_match()
   $int = 1234;
if(preg_match("/^[0-9]{2,3}$/",$int)){
    echo 'マッチ!';
    }else{
    echo 'マッチしない';
   }
   
■ nl2br()
   改行コードを
タグに変換して表示する
   $text = "1行目'."\n".'2行目'."\n".'3行目";
   echo nl2br($text);
   
■ mb_strlen()
   文字列の長さを調べる
   $moji = '毎日しあわせだな~';
   $moji_str = mb_strlen($moji,'UTF-8');

■ mb_substr()
   $text = 'あれはドラエモン';
   echo mb_substr($text,0,2,'UTF-8');//1文字目から2つ取り出した

■ mb_substr()
   $text = 'あれはドラエモン';
   echo mb_substr($text,0,2,'UTF-8');//1文字目から2つ取り出した
   
■ preg_match_all()
   $pattern = "/[※].*\n/u";
   preg_match_all($pattern,$text,$match);
   パターンにマッチした文字列が
   $match[0][0]から順番に格納される (2個目のデータなら $match[0][1]となる)
   
■ trim()
   $moji = "---ららら---";
   echo trim("-",$moji);
   
■ header()
   header("Location: test.php");
   
■ unset()
   変数、セッション変数や配列の値を破棄
   unset($_SESSION['err_msg']);
   
■ in_array()
   $str = array('北海道','東京','大阪','沖縄');
   $timei = '京都';
   if(in_array($timei,$str)){
echo '京都は含まれています';
   }else{
echo '京都は含まれていません';
   }

■ mb_strimwidth()
   0から15文字まで表示される
   $str = mb_strimwidth($str, 0, 15, "...", 'UTF-8');

■ mb_convert_kana()
   $str = mb_convert_kana( "アイウエオ123456789", "ak", 'utf-8' );

■ array_unique(配列,比較方法)
   配列の中に重複したものを削除
   $array = array(0,1,2,3,4,5,0,1);
   $new_array = array_unique($array);

   
■ $new_params = array_merge($default_params, $params);

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16