LoginSignup
2
2

More than 5 years have passed since last update.

[関数系] str_replaceの罠 ~nullを添えて~

Posted at

概要

str_replaceを使っていてまじかと思ったことをメモ。

str_replace

まずは仕様を確認

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

この関数は、subject の中の search を全て replace に置換します。
(正規表現のような) 技巧的な置換ルールを必要としない場合、 preg_replace() の代わりにこの関数を常用するべきです。

php -aとかで確かめてみる。

sample_null.php
var_dump(str_replace('sample', 'sample', null));

こうすると、結果は

php > var_dump(str_replace('sample','sample',null));
string(0) ""

となる。

・・・空文字・・・だと・・・!?

みなさんnullが入ってきそうな箇所でstr_replaceを使う時には気をつけましょう。

 おまけ

なぜnullが空文字になるのかソースコードを読みにいってみた。
ついでに数値が数字になって返ってきたりもしているため、なんか変換処理がありそうな気がした。
そうしたら多分ここなんじゃねーかみたいなところがあった。

string.c(php_str_replace_commonメソッド)[4450行付近]
|  | /* Make sure we're dealing with strings and do the replacement. */ |
|--:|:--|:--|:--|
|  | if (Z_TYPE_P(search) != IS_ARRAY) { |
|  |  | convert_to_string_ex(search); |
|  |  | if (Z_TYPE_P(replace) != IS_STRING) { |
|  |  |  | convert_to_string_ex(replace); |
|  |  | } |
|  | } else if (Z_TYPE_P(replace) != IS_ARRAY) { |
|  |  | convert_to_string_ex(replace); |
|  | } |

このようにstringでない場合にはconvert_to_string_exという自作関数を利用して変換をかけており、おそらくこれをそのまま返している。まだ最後まで読んでいないので、ちゃんとしたことは言えないけど、多分これがそのまま返されているためだと思われる。ちゃんと読んだら追記する。

参考

str_replace - php.net

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