2

This question relates to an existing topic here..

Remove first 4 characters of a string with PHP

but instead what if i would like to remove specific number of characters from a specific index of a string?

e.g

(i want to remove 8 characters from the fourth index)
$input = 'asdqwe123jklzxc';
$output = 'asdlzxc';
Community
  • 1
  • 1
CudoX
  • 985
  • 2
  • 19
  • 31

4 Answers4

8

I think you need this:

echo substr_replace($input, '', 3, 8);

More information here:

http://www.php.net/manual/de/function.substr-replace.php

Hammurabi
  • 305
  • 1
  • 3
  • 7
4
$input = 'asdqwe123jklzxc';
echo str_replace(substr($input, 3, 8), '', $input);

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 1
    This may replace more than intended if the string found by substr has more than one occurrence in $input. The answer by Hammurabi below is better in that case. – Oylex Nov 10 '16 at 15:30
  • This is not the correct answer. It has a huge technical mistake as pointed out by @Oylex – Omar Tariq Oct 03 '18 at 07:07
0

You can try with:

$output = substr($input, 0, 3) . substr($input, 11);

Where 0,3 in first substr are 4 letters in the beggining and 11 in second is 3+8.

For better expirience you can wrap it with function:

function removePart($input, $start, $length) {
  return substr($input, 0, $start - 1) . substr($input, $start - 1 + $length);
}

$output = removePart($input, 4, 8);
hsz
  • 148,279
  • 62
  • 259
  • 315
0

I think you can try :

function substr_remove(&$input, $start, $length) {
    $subpart = substr($input, $start, $length);
    $input = substr_replace($input, '', $start, $length);
    return $subpart;
}