1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP正規表現での末尾改行

Posted at

PHPで制御文字以外の文字入力を許可したかったが、
なぜか末尾改行が許可されてしまったので調べてみました。

文字列の末尾にだけマッチさせたい場合には「¥z」を使うということなので「$」と比較してみました。
結果、思い通りの動作になったのでメモ。

まずは「$」の場合
なぜか末尾改行がfilter_varを通ってしまう・・・

$options = ['options' => [
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
    'regexp' => '/^[[:^cntrl:]]{0,5}$/u',
]];

$var = filter_var("アイ\nウ07", FILTER_VALIDATE_REGEXP, $options);
echo '"アイ\nウ07"'."\n";
var_dump($var);
echo "\n";

$var = filter_var("アイウ07\n", FILTER_VALIDATE_REGEXP, $options);
echo '"アイウ07\n"'."\n";
var_dump($var);
echo "\n";

$var = filter_var("アイ\n", FILTER_VALIDATE_REGEXP, $options);
echo '"アイ\n"'."\n";
var_dump($var);
echo "\n";

$var = filter_var("\nウ07", FILTER_VALIDATE_REGEXP, $options);
echo '"\nウ07"'."\n";
var_dump($var);
echo "\n";

$var = filter_var("\n\nウ07", FILTER_VALIDATE_REGEXP, $options);
echo '"\n\nウ07"'."\n";
var_dump($var);
echo "\n";

$var = filter_var("\n", FILTER_VALIDATE_REGEXP, $options);
echo '"\n"'."\n";
var_dump($var);
echo "\n";

$var = filter_var("アイウ07", FILTER_VALIDATE_REGEXP, $options);
echo '"アイウ07"'."\n";
var_dump($var);
echo "\n";

$var = filter_var("", FILTER_VALIDATE_REGEXP, $options);
echo '""'."\n";
var_dump($var);
echo "\n";

「$」の判定結果(末尾改行がfalseにならない)


"アイ\nウ07"
bool(false)

"アイウ07\n"
string(12) "アイウ07
"

"アイ\n"
string(7) "アイ
"

"\nウ07"
bool(false)

"\n\nウ07"
bool(false)

"\n"
string(1) "
"

"アイウ07"
string(11) "アイウ07"

""
string(0) ""

「$」ではなく「\z」に変更
思い通りfilter_varで判定できました。

$options = ['options' => [
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
    'regexp' => '/^[[:^cntrl:]]{0,5}\z/u',
]];

以下上と同じ

「\z」の判定結果(末尾改行もfalse)

"アイ\nウ07"
bool(false)

"アイウ07\n"
bool(false)

"アイ\n"
bool(false)

"\nウ07"
bool(false)

"\n\nウ07"
bool(false)

"\n"
bool(false)

"アイウ07"
string(11) "アイウ07"

""
string(0) ""
1
1
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?