3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php function mb_str_replace($search, $replace, $subject, $encoding = 'auto') { if(!is_array($search)) { $search = array($search); } if(!is_array($replace)) { $replace = array($replace); } if(strtolower($encoding) === 'auto') { $encoding = mb_internal_encoding(); } // $subject が複数ならば各要素に繰り返し適用する if(is_array($subject) || $subject instanceof Traversable) { $result = array(); foreach($subject as $key => $val) { $result[$key] = mb_str_replace($search, $replace, $val, $encoding); } return $result; } $currentpos = 0; // 現在の検索開始位置 while(true) { // $currentpos 以降で $search のいずれかが現れる位置を検索する $index = -1; // 見つけた文字列(最も前にあるもの)の $search の index $minpos = -1; // 見つけた文字列(最も前にあるもの)の位置 foreach($search as $key => $find) { if($find == '') { continue; } $findpos = mb_strpos($subject, $find, $currentpos, $encoding); if($findpos !== false) { if($minpos < 0 || $findpos < $minpos) { $minpos = $findpos; $index = $key; } } } // $search のいずれも見つからなければ終了 if($minpos < 0) { break; } // 置換実行 $r = array_key_exists($index, $replace) ? $replace[$index] : ''; $subject = mb_substr($subject, 0, $minpos, $encoding) . // 置換開始位置より前 $r . // 置換後文字列 mb_substr( // 置換終了位置より後ろ $subject, $minpos + mb_strlen($search[$index], $encoding), mb_strlen($subject, $encoding), $encoding); // 「現在位置」を $r の直後に設定 $currentpos = $minpos + mb_strlen($r, $encoding); } return $subject; } $test = 'this is {$tableName} test'; echo mb_str_replace('{$tableName}', 'timecard', $test);
Output for 5.0.0 - 7.1.0
this is timecard test
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING in /in/h8i7Q on line 14
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.4.1
Parse error: parse error, unexpected T_STRING in /in/h8i7Q on line 14
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error in /in/h8i7Q on line 14
Process exited with code 255.