Extracting and replacing substrings
suggest changeSingle bytes can be extracted with square-bracket syntax. A UTF-8 character can occupy more than one byte. For more than one byte, use a function such as substr.
String offsets start at 0.
$foo = 'Hello world';
$foo[6]; // returns 'w'
substr($foo, 6, 1); // also returns 'w'
substr($foo, 6, 2); // returns 'wo'
Strings can also be changed one character at a time using square bracket syntax. Replacing more than one character requires a function such as substr_replace.
$foo = 'Hello world';
$foo[6] = 'W'; // $foo is now 'Hello World'
$foo = 'Hello world';
substr_replace($foo, 'W', 6, 1); // returns 'Hello World'; $foo is unchanged
substr_replace($foo, 'Whi', 6, 2); // returns 'Hello Whirled'
// substr_replace() returns a new string. The replacement need not be the same length.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents