CudoX
CudoX

Reputation: 1013

php remove n chars from nth index of a string

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';

Upvotes: 2

Views: 5927

Answers (4)

Quyền Lê
Quyền Lê

Reputation: 1

I think you can try :

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

Upvotes: 0

Hammurabi
Hammurabi

Reputation: 305

I think you need this:

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

More information here:

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

Upvotes: 8

hsz
hsz

Reputation: 152304

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);

Upvotes: 0

John Conde
John Conde

Reputation: 219934

$input = 'asdqwe123jklzxc';
echo str_replace(substr($input, 3, 8), '', $input);

Demo

Upvotes: 4

Related Questions