Home php How do I insert a tab character into a string?

How do I insert a tab character into a string?

Author

Date

Category

This adds a question symbol in a black vertical diamond to the text:

$ s = 'Just text';
$ str [4] = "\ t";

Utf-8 encoding


Answer 1

This is how it is done. First, use mb_str_split () to convert the string to an array. Make a copy of it. After that, with each array, make a slice at the desired position using array_slice () (one before, the other after). At the end, combine the arrays, and between them your desired piece of text. Finally, convert the result to a string using implode ().

The problem, as we noticed earlier, is due to unicode, so you have to go to some tricks.


Answer 2

Most likely so-so, but just as an option: https://ideone.com/yagsbJ

& lt;? php
$ s = 'Just Text';
$ s = preg_replace ('/ ^ (. {3}) ./ u', "$ 1 \ t", $ s);
echo $ s;

Answer 3

You cannot work with multibyte encodings using direct indices – you are addressing not characters, but bytes.

function replaceStrAt ($ str, $ substr, $ from, $ to = null) {
 is_null ($ to) and $ to = $ from;
 return mb_substr ($ str, 0, $ from). $ substr. mb_substr ($ str, $ to + 1);
}
function insertSubstrInto ($ str, $ substr, $ index) {
 return mb_substr ($ str, 0, $ index). $ substr. mb_substr ($ str, $ index);
}
$ s = 'And just text';
echo replaceStrAt ($ s, "\ t", 4), "\ n"; // And just a hundred text
echo insertSubstrInto ($ s, "\ t", 4), "\ n"; // And just the text

Demo

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions