Replace or insert characters into a string based on a numeric position in the string
Asked Answered
D

6

33

Is there a function in PHP that takes in a string, a number (i), and a character (x), then replaces the character at position (i) with (x)?

If not, can somebody help me in implementing a function which can replace or insert a substring?

Dysgraphia answered 22/10, 2010 at 6:2 Comment(3)
S
68
$str    = 'bar';
$str[1] = 'A';
echo $str; // prints bAr

or you could use the library function substr_replace as:

$str = substr_replace($str,$char,$pos,1);
Stomy answered 22/10, 2010 at 6:4 Comment(7)
Ref: php.net/manual/en/…Crude
does this work as expected with unicode strings where the characters are all multibyte?Italian
@Crude What could I do if I want to remove the a to get final string br?Bresnahan
@sємsєм Perhaps you want $str = substr_replace($str, 'a', '')Crude
@Crude No I mean removing character by its position in the string.Bresnahan
@sємsєм First off, I meant str_replace('a', '', $str) in my prior comment. If you want to remove a character by its position in the string, just use '' as the replacement string. $str = substr_replace($str,'',$pos,1); If you have further questions, you should really start your own new SO question.Crude
Note that above will not work for an empty string. $str = ""; $str[0]='A' after that $str becomes an array... Go figure ;-).Pinder
M
15

I amazed why no one remember about substr_replace()

substr_replace($str, $x, $i, 1);
Mythos answered 22/10, 2010 at 6:24 Comment(0)
F
4

Codaddict is correct, but if you wanted a function, you could try...

function updateChar($str, $char, $offset) {

   if ( ! isset($str[$offset])) {
       return FALSE;
   }

   $str[$offset] = $char;

   return $str;

}

It works!

Filicide answered 22/10, 2010 at 6:8 Comment(0)
E
1
function replace_char($string, $position, $newchar) {
  if(strlen($string) <= $position) {
    return $string;
  }
  $string[$position] = $newchar;
  return $string;
}

It's safe to treat strings as arrays in PHP, as long as you don't try to change chars after the end of the string. See the manual on strings:

Elysian answered 22/10, 2010 at 6:9 Comment(1)
...and all of characters before and at the designated position are all single-byte characters. Accessing characters by their offset is less intuitive and prone to mistakes when multibyte strings are involved.Zomba
P
0
implode(':', str_split('1300', 2));

returns:

13:00

Also very nice for some credit card numbers like Visa:

implode(' ', str_split('4900000000000000', 4));

returns:

4900 0000 0000 0000

str_split — Convert a string to an array

Picrite answered 13/1, 2017 at 21:35 Comment(1)
This doesn't look like what he's asking for. For example, if he wanted to add a colon in the 11th position of "I will need tomatoes, peppers and onions", your suggestion would not produce the desired result.Dichotomy
Z
0

substr_replace() is capable of replacing n number of characters bytes starting from x offset (positive or negative) in a given string with another string and has an optional parameter for limiting the number of characters bytes consumed before injecting the replacement string.

Multibyte strings are fine to use, but the offset and length parameters will count each byte of the multibyte characters.

Examples: (Demo)

echo substr_replace('stack',  'i',    2,  1);  // stick
echo substr_replace('stack',  'u',   -3,  1);  // stuck
echo substr_replace('stack',  'o',    1,  2);  // sock
echo substr_replace('stack',  'ge',  -2,  2);  // stage
echo substr_replace('stack',  'bri',  0,  3);  // brick
echo substr_replace('stack',  'hre',  1, -1);  // shrek
echo substr_replace('stack',  'hre', -4, -1);  // shrek
echo substr_replace('stack',  'y',    3,  0);  // stayck   ...consume no bytes
echo substr_replace('stack',  'y',    3);      // stay     ...consume remaining bytes
echo substr_replace('voilà',  'ci',  -2);      // voilci   ...à has two bytes
echo substr_replace('voilà',  'ci',  -3);      // voici    ...à has two bytes
echo substr_replace('sûreté', '',     4);      // sûr      ...û has two bytes
Zomba answered 4/12, 2023 at 23:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.