note 73312 deleted from language.types.string by felipe

From: Date: Sun, 23 Mar 2008 23:15:03 +0000
Subject: note 73312 deleted from language.types.string by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-137441@lists.php.net to get a copy of this message
Note Submitter: thomas dot oldbury dot nospam at tgohome dot com ---- This function I created to insert a string at a position or an array of positions. Quite useful. <?php /* string strwpos (string insert, string input, int position [, int mode]) Returns a string with a string inserted at a position, or an array of positions. Normally, the string is inserted on the right of the position, but it can be inserted on the left or both. The following constants define where the string should be inserted: INS_LEFT - insert the string left of the position INS_RIGHT - insert the string right of the position INS_BOTH - insert the string on both sides Returns resulting string on success, FALSE on failure. */ define('INS_LEFT', 0); define('INS_RIGHT', 1); define('INS_BOTH', 2); function strwpos($ins, $string, $pos, $mode = INS_RIGHT) { $str = ""; for($c = 0; $c < strlen($string); $c++) { if(is_array($pos)) { if(in_array($c, $pos, true)) { if($mode == INS_RIGHT) { $ins_c = substr($string, $c, 1) . $ins; } elseif($mode == INS_LEFT) { $ins_c = $ins . substr($string, $c, 1); } elseif($mode == INS_BOTH) { $ins_c = $ins . substr($string, $c, 1) . $ins; } else { trigger_error("Unknown mode '$mode' specified", E_USER_WARNING); return false; } $str .= $ins_c; } else { $str .= $string[$c]; } } else { if($c == $pos) { if($mode == INS_RIGHT) { $ins_c = substr($string, $c, 1) . $ins; } elseif($mode == INS_LEFT) { $ins_c = $ins . substr($string, $c, 1); } elseif($mode == INS_BOTH) { $ins_c = $ins . substr($string, $c, 1) . $ins; } else { trigger_error("Unknown mode '$mode' specified", E_USER_WARNING); return false; } $str .= $ins_c; } else { $str .= $string[$c]; } } } return $str; } ?> This function can have a few problems. For example, the following code will produce an unexpected result: <?php echo strwpos('love, not ', 'I hate you', 2); ?> It will produce this result: I hlove, not ate you The reason for this is because the string is inserted to the right of the string by default. So using the optional MODE parameter with the INS_LEFT value will produce the result we need. <?php echo strwpos('love, not ', 'I hate you', 2, INS_LEFT); ?> This will produce the result we need: I love, not hate you You can also use an array of places to insert the string into: <?php echo strwpos('brown ', 'The quick fox jumped over the lazy dog', array(10, 35), INS_LEFT); ?> This will produce the result: The quick brown fox jumped over the lazy brown dog Hope this helps.

« previous php.notes (#137441) next »