PHP
56
str replacepos
Guest on 20th June 2022 04:54:54 PM
<?php
/**
* Add a tag around a character and return the number of positions added
* @param string String to be replaced
* @param tabPos Array of character position
* @param start String placed at the start of the character
* @param end String placed at the end of the character
* @return string with the characters surrounded.
*Note the algorithm is a little more complicated because of the 2-byte UTF8 characters.
*/
function str_replacepos($string, $arrPos, $start, $end) {
$return = '';
if ( ($c=count ($tabPos)) ) {
$fixUTF8=0;
foreach($arrPos as $pos) {
$pos+=$correctionUTF8;
$return .= substr($string, $lastpos, $pos-$lastpos);
$letter = $string{$pos};
if ( ord($letter) > 127 ) {
$return .= $start . $letter . $string{++$pos} . $end;
$fixUTF8++;
} else {
$return .= $start . $string{$pos} . $end;
}
$lastpos = $pos+1;
}
$return .= substr($string, $lastpos, strlen($string)-$lastpos);
} else {
$return = $string;
}
return $return;
}
function run_test() {
echo str_replacepos
('abcd', array(0,1,3), '[', ']')."\n"; // [a][b]c[d]
echo str_replacepos
('abcd', array(1,3), '[', ']')."\n"; // a[b]c[d]
echo str_replacepos
('aécd''
, array(1,3), '
['
, '
]'
)."\n"
;// a[e]c[d]
}
?