LoginSignup
1
1

More than 3 years have passed since last update.

preg_match は型変換されてマッチングする

Last updated at Posted at 2019-09-19

preg_match の第 2 引数には検索対象の文字列を渡します。

preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) : int

別の型を渡したらどうなるか確認します。

ちなみに preg_match の返り値は下記です。

返り値

preg_match() は、pattern が指定した subject にマッチした場合に 1 を返します。 マッチしなかった場合は 0、エラーが発生した場合は FALSE を返します。

引用:PHP: preg_match - Manual

論理型が文字列型に変換された場合、下記のようになります。

boolean の TRUE は文字列の "1" に、 FALSE は "" (空文字列) に変換されます。 これにより boolean と文字列の値を相互に変換することができます。

引用:文字列への変換

<?php

class A {}

$int = 111;
$float = 1.23;
$bool_true = true;
$bool_false = false;
$array = ['aaa'];
$obj = new A;

var_dump(preg_match('/111/', $int));
var_dump(preg_match('/1.23/', $float));
var_dump(preg_match('/1/', $bool_true));
var_dump(preg_match('/^$/', $bool_false));
var_dump(preg_match('/Array/', $array));
var_dump(preg_match('/A/', $obj));
結果
int(1)
int(1)
int(1)
int(1)

Warning: preg_match() expects parameter 2 to be string, array given in /in/HVBhj on line 16
bool(false)

Warning: preg_match() expects parameter 2 to be string, object given in /in/HVBhj on line 17
bool(false)

実行結果:3v4l

結果を見ると整数型、浮動小数点数型、論理型は文字列に変換されてマッチングします。

配列とオブジェクトは変換されず、エラー false が返ります。

1
1
0

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
1
1