A
A
Alexander Tokmakov2018-03-16 11:32:02
PHP
Alexander Tokmakov, 2018-03-16 11:32:02

How to insert a word after a certain number of characters + before a space?

Actually here is the code:

$s = "Очень длинное пр едложение каждый раз  разное поэтому привязки к определенным символам класс ам нет и не будет";
            $str = str_replace (" ", "", $s);
            $kol_bukv = strlen ($str);
 
            if($kol_bukv > 30){

    $add = '[spoler]';
                $pos = 30; //в какую позицию исходно строки вставить добавочную стоку
                $result = substr($s, 0, $pos).$add.substr($s, -$pos);
                echo $result; 


            }else{
                echo $s;
            }

the following is displayed:
"There is no and will not be a very long pr[spoler]"
it should be displayed like this:
"A very long sentence [spoler] is different every time, therefore there is no and will not be a binding to certain characters to classes"
that is, count 30 characters, then reach before a space, put " [spoler] " and continue the text further.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick Sdk, 2018-03-16
@calliko

$s = "Очень длинное предложение каждый раз  разное поэтому привязки к определенным символам класс ам нет и не будет";
$insert = '[spoiler]';
$str = preg_replace('#^(.{30}\S*?) #', "$1 {$insert} ", $s);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question