MB34
MB34

Reputation: 4404

Remove character at nth offset from string

I need to know how to do this reliably with the least amount of calls.

I have a string and I need to remove the 8th character from it. It doesn't matter what the char is, I just need to remove ONLY the 8th char.

I came up with this but a little too unwieldy for me.

//      12345678901234567890
$str = '5NMSG3AB1AH353158';
// after removing char, result should be:
// 5NMSG3A1AH353158
$r = str_split($str);
unset($r[7]);
echo join('', $r);

Possibly Regex?

Upvotes: 0

Views: 120

Answers (3)

steffen
steffen

Reputation: 16948

Here are some solutions:

$str = substr($str, 0, 7) . substr($str, 8);
$str = substr_replace($str, '', 7, 1);
$str = preg_replace('/(.{7})./', '$1', $str, 1);
$str = preg_replace('/.{7}\K./', '', $str, 1);

I'd go for substr() or better substr_replace() as this will certainly be fastest and most easy to read.

Upvotes: 2

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

Like this

$str = '5NMSG3AB1AH353158';
echo preg_replace('/^(.{7})./', '\1', $str);

Output:

5NMSG3A1AH353158

Sandbox

Explanation

  • ^ start of string
  • (...) capture
  • . match any
  • {7} seven times
  • . match any one time

Then the replacement

  • \1 first capture group

Basically capture the first 7 chars, then match the 8th, and replace that with the captured 7 chars. Which effectively removes the 8th.

UPDATE

here is another way I like (I haven't used that function sense college, I think):

$s = '5NMSG3A1AH353158';
echo substr_replace($s,'',7,1); //strings are 0 based

sandbox

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.

mixed substr_replace( mixed $string, mixed $replacement, mixed $start [, mixed $length ] )

http://php.net/manual/en/function.substr-replace.php

Simple.

Upvotes: 1

Don't Panic
Don't Panic

Reputation: 41810

substr_replace makes this very simple.

$string = substr_replace($string, '', 7, 1);

It can also take an array of strings as its first parameter, and do the same replacement in all of them, which can be pretty handy.

Upvotes: 1

Related Questions