PHP   56

str replacepos

Guest on 20th June 2022 04:54:54 PM

  1. <?php
  2. /**
  3.  * Add a tag around a character and return the number of positions added
  4.  * @param string String to be replaced
  5.  * @param tabPos Array of character position
  6.  * @param start String placed at the start of the character
  7.  * @param end String placed at the end of the character
  8.  * @return string with the characters surrounded.
  9.  *Note the algorithm is a little more complicated because of the 2-byte UTF8 characters.
  10.  */
  11. function str_replacepos($string, $arrPos, $start, $end) {
  12.  $return = '';
  13.  if ( ($c=count ($tabPos)) ) {
  14.   $fixUTF8=0;
  15.   foreach($arrPos as $pos) {
  16.    $pos+=$correctionUTF8;
  17.    $return .= substr($string, $lastpos, $pos-$lastpos);
  18.    $letter = $string{$pos};
  19.    if ( ord($letter) > 127 ) {
  20.     $return .= $start . $letter . $string{++$pos} . $end;
  21.     $fixUTF8++;
  22.    } else {
  23.     $return .= $start . $string{$pos} . $end;
  24.    }
  25.    $lastpos = $pos+1;
  26.   }
  27.   $return .= substr($string, $lastpos, strlen($string)-$lastpos);
  28.  } else {
  29.   $return = $string;
  30.  }
  31.  return $return;
  32. }
  33.  
  34. function run_test() {
  35.  echo str_replacepos('abcd', array(0,1,3), '[', ']')."\n"; // [a][b]c[d]
  36.  echo str_replacepos('abcd', array(1,3), '[', ']')."\n"; // a[b]c[d]
  37.  echo str_replacepos('aécd'', array(1,3), '[', ']')."\n";// a[e]c[d]
  38.  
  39. }
  40. ?

Raw Paste


Login or Register to edit or fork this paste. It's free.