preg_match()
やpreg_grep()
の検索パターンのとこに変数や配列の要素を使用したい時の書き方。
目次
preg_match()
変数を検索パターンに使用する
実はそのままぶち込めばOK
$hoge = "ほげ";
$hogehoge = "〜ほげ〜";
if ( preg_match( "/$hoge/", $hogehoge ) ) {
echo "あったよ.";
} else {
echo "なかったよ.";
}
このほか、preg_match("/${hoge}/", $hogehoge)
でもいいし、preg_match("/".$hoge."/", $hogehoge)
でも問題なかった。
配列を検索パターンに使用する
実はこれもそのままぶちこめる
$hoge = ["ほげ", "hoge"];
$hogehoge = "〜ほげ〜";
if ( preg_match( "/$hoge[0]/", $hogehoge ) ) {
echo "あったよ.";
} else {
echo "なかったよ.";
}
先ほどと同様、このほかにもpreg_match("/${hoge[0]}/", $hogehoge)
でもいいし、preg_match("/".$hoge[0]."/", $hogehoge)
でも問題なかった。
preg_grep()
preg_match()と同じです。
$hoge = "ほげ";
$hoge_arr = ["hoge", "~ほげ〜"];
if ( preg_grep( "/$hoge/", $hoge_arr ) ) {
echo "あったよ.";
} else {
echo "なかったよ.";
}
コメント