удаление переносов строк php

Удаление переносов строк php

(PHP 4, PHP 5, PHP 7, PHP 8)

trim — Удаляет пробелы (или другие символы) из начала и конца строки

Описание

Список параметров

Обрезаемая строка ( string ).

Возвращаемые значения

Примеры

Пример #1 Пример использования trim()

Результат выполнения данного примера:

Пример #2 Обрезание значений массива с помощью trim()

Результат выполнения данного примера:

Примечания

Замечание: Возможные трюки: удаление символов из середины строки

Смотрите также

User Contributed Notes 18 notes

When specifying the character mask,
make sure that you use double quotes

= »
Hello World » ; //here is a string with some trailing and leading whitespace

Non-breaking spaces can be troublesome with trim:

// PS: Thanks to John for saving my sanity!
?>

It is worth mentioning that trim, ltrim and rtrim are NOT multi-byte safe, meaning that trying to remove an utf-8 encoded non-breaking space for instance will result in the destruction of utf-8 characters than contain parts of the utf-8 encoded non-breaking space, for instance:

non breaking-space is «\u» or «\xc2\xa0» in utf-8, «µ» is «\u» or «\xc2\xb5» in utf-8 and «à» is «\u» or «\xc3\xa0» in utf-8

$input = «\uµ déjà\u«; // » µ déjà «
$output = trim($input, «\u«); // «▒ déj▒» or whatever how the interpretation of broken utf-8 characters is performed

$output got both «\u» characters removed but also both «µ» and «à» characters destroyed

Care should be taken if the string to be trimmed contains intended characters from the definition list.

E.g. if you want to trim just starting and ending quote characters, trim will also remove a trailing quote that was intentionally contained in the string, if at position 0 or at the end, and if the string was defined in double quotes, then trim will only remove the quote character itself, but not the backslash that was used for it’s definition. Yields interesting output and may be puzzling to debug.

To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

trim is the fastest way to remove first and last char.

This is the best solution I’ve found that strips all types of whitespace and it multibyte safe

Trim full width space will return mess character, when target string starts with ‘《’

[EDIT by cmb AT php DOT net: it is not necessarily safe to use trim with multibyte character encodings. The given example is equivalent to echo trim(«\xe3\80\8a», «\xe3\x80\x80»).]

if you are using trim and you still can’t remove the whitespace then check if your closing tag inside the html document is NOT at the next line.

there should be no spaces at the beginning and end of your echo statement, else trim will not work as expected.

If you want to check whether something ONLY has whitespaces, use the following:

Источник

Как убрать все переносы строк с помощью RegEx?

Как можно выбрать все переносы строк и заменить их пустой строкой? Пытался сделать так:

Можно, конечно, заменить не на пустую строку, а на тот же символ переноса. Но можно ли получить желаемый результат без замены на перенос строки?

удаление переносов строк php. Смотреть фото удаление переносов строк php. Смотреть картинку удаление переносов строк php. Картинка про удаление переносов строк php. Фото удаление переносов строк php

2 ответа 2

Вы можете использовать

Выражение /[\r\n]+/g находит все совпадения одного и более знаков перевода каретки (CR, \x0D ) или переноса строки (LF, \x0A ) и шаблон замены ‘\n’ заменяет их одним знаком LF.

Пример работы кода на JavaScript:

Получилось получить желаемый результат следующим выражением:

удаление переносов строк php. Смотреть фото удаление переносов строк php. Смотреть картинку удаление переносов строк php. Картинка про удаление переносов строк php. Фото удаление переносов строк php

Всё ещё ищете ответ? Посмотрите другие вопросы с метками javascript регулярные-выражения или задайте свой вопрос.

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.28.40331

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *