Удалить перевод строки 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
$input = «\u
$output = trim($input, «\u
$output got both «\u
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?
Как можно выбрать все переносы строк и заменить их пустой строкой? Пытался сделать так:
Можно, конечно, заменить не на пустую строку, а на тот же символ переноса. Но можно ли получить желаемый результат без замены на перенос строки?
2 ответа 2
Вы можете использовать
Выражение /[\r\n]+/g находит все совпадения одного и более знаков перевода каретки (CR, \x0D ) или переноса строки (LF, \x0A ) и шаблон замены ‘\n’ заменяет их одним знаком LF.
Пример работы кода на JavaScript:
Получилось получить желаемый результат следующим выражением:
Всё ещё ищете ответ? Посмотрите другие вопросы с метками javascript регулярные-выражения или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.17.40238
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Функции для работы со строками
Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.
Содержание
User Contributed Notes 24 notes
In response to hackajar yahoo
No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11’s «Strings» article under the «String access and modification by character» heading.
I’m converting 30 year old code and needed a string TAB function:
//tab function similar to TAB used in old BASIC languages
//though some of them did not truncate if the string were
//longer than the requested position
function tab($instring=»»,$topos=0) <
if(strlen($instring)
I use these little doo-dads quite a bit. I just thought I’d share them and maybe save someone a little time. No biggy. 🙂
Just a note in regards to bloopletech a few posts down:
The word «and» should not be used when converting numbers to text. «And» (at least in US English) should only be used to indicate the decimal place.
Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
/*
* example
* accept only alphanum caracteres from the GET/POST parameters ‘a’
*/
to: james dot d dot baker at gmail dot com
PHP has a builtin function for doing what your function does,
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.
Any string can (usually) be thought of as being in one of these ‘modes’:
pure = what the user actually typed / what you want to see on the page /
what is actually stored in the DB
gpc = incoming GET, POST or COOKIE data
sql = escaped for passing safely to RDBMS via SQL (also, data from DB
queries and file reads if you have magic_quotes_runtime on—which
is rare)
html = safe for html display (htmlentities applied)
Always knowing what mode your string is in—using these methods to
convert between modes—will prevent SQL injection and cross-site scripting.
This class refers to its own namespace (so it can work in PHP 4—there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.
Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST[‘username’]);
*/
Example: Give me everything up to the fourth occurance of ‘/’.
//
// string strtrmvistl( string str, [int maxlen = 64],
// [bool right_justify = false],
// [string delimter = «
\n»])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to ‘spread’ a string over two lines.
//
I really searched for a function that would do this as I’ve seen it in other languages but I couldn’t find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.
?>
Example: Give me everything up to the fourth occurance of ‘/’.
The functions below:
Are correct, but flawed. You’d need to use the === operator instead:
Here’s an easier way to find nth.
I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn’t work for me. I found the algorithm at http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function
Here’s a simpler «simplest» way to toggle through a set of 1..n colors for web backgrounds:
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.
(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)
/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/
?>
Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using
, and then you can use this function to only return text up to the N’th
.
You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().
= ‘Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.’ ;
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida
Популярные примеры работы регулярных выражений в PHP
Вопросов по данной теме уйма. И я решил создать свою подборку регулярных выражений. Думаю многим поможет!
Примеры preg_replace PHP
1. Удаляем определённую ссылку в переменной text
2. Удаляем комментарии в переменной text
3. Удаляем спецсимволы
4. Удаляем всё, что между
5. Удаляем всё, что между
6. Удаляем конкретные символы из строки
7. Удаляем пробелы по бокам строки и обычные пробелы
8. Удаляем лишние переводы строк и переносы
9. Удаляем расширения в названиях файлов
10. Создаём функцию обработки текста
11. Найти содержимое определённого тега и вставить его в другие теги
13. Добавить или убрать текст в начале или конце переменной с текстом
14. Находим все http:// и заменяем на ссылки
15. Удаление GET-параметров из URL
16. Добавить тег br в начало или конец строк
17. Как конвертировать html в текст
18. Как разобрать email и сделать ссылку
Примеры preg_match PHP
1. проверка mail адреса на корректность
2. Найти mail адреса в тексте
3. Является ли переменная числом, длиной от 13 до 16 символов (проверка кредитной карты)
4. Проверка имени файла
5. Ищем в тексте мобильные телефоны РФ
6. Состоит ли строка только из букв, цифр и _, длиной от 8 до 20 символов:
7. Есть ли в строке идущие подряд символы, не менее 3-х символов подряд (типа абвгДДДеё, но не ааббаабб):
8. Поиск в разных частях строки конструкции:
9. Проверки на тип браузера. Возвращает true если browser = Netscape 2, 3 or MSIE 3.
Примеры ereg PHP
1. Проверка mail адреса в тексте
Как удалить концы строк из текста средствами РНР
Задача удаления концов строчек из (многострочной) строки текста бывает обусловлена, к примеру, когда такая строка прочитана из текстового файла. В этой статье рассмотрим, насколько эффективны различные способы такого удаления.
Символы концов строк
В операционной системе Linux конец строки обозначается символом \n (или LF ), а в Windows – двумя символами: \r \n ( CR LF ). Обратите внимание, что слеш \ и идущая после него буква ( r или n ) является ОДНИМ байтом (т.е. 1 байт), хотя для его обозначения требуется ДВА текстовых символа.
Так как файл может быть записан как в Windows, так и в Linux, будем удалять, для надежности, и тот, и другой символы.
Способы удаления концов строк
Рассмотрим наиболее известные пять способов (функции) для удаления концов строк:
1. Функция str_replace
2. Функция rtrim()
3. Функция preg_replace()
Эта функция производит удаление концов строк путем применения регулярного выражения. При работе с содержимым, прочитанным из файла, как с отдельной строкой, эта функция работает на порядок дольше, чем ранее обсуждавшиеся функции. А вот при обработке содержимого файла, как отдельных строк массива, эта функция показывает гораздо лучший результат. Результаты тестирования приведены ниже.
Программный код
Для тестирования различных подходов использовался следующий программный код на РНР:
Как видно, этот код последовательно удаляет концы строк из содержимого, считанного из файла. Для примера, взят файл карты сайта Sitemap.xml, находящийся в корневом каталоге сайта. Этот файл имел размер 59,7 кБ, содержал 2250 строчек.
Каждый из четырех способов удаления концов строк, для статистики, применяется 20 раз. Затем результаты усредняются. И вот что получилось:
time1_all (array, str_replace)=0.0055
time2_all (array, rtrim)=0.0027
time3_all (string, str_replace)=0.0021
time4_all (string, preg_replace)=0.0235
time5_all (array, preg_replace)=0.0064
Тогда как в аналогичном цикле, функция str_replace() показала в 2 раза более медленный результат.
Ну, а что касается регулярного выражения, примененного к содержимому файла в целом, тут даже и говорить не приходится: время выполнения увеличилось на порядок! Хотя, при разбиении файла на строчки и создании соответствующего массива, функция preg_replace() работает быстрее. Но, даже и в этом случае – чисто строковые функции (без регулярных выражений) работают быстрее.
Выводы
Итак, наверное, банально, но, все же, стоит отметить:
Обобщение
В целом же, можно сделать такой вывод
. Не стоит использовать первую попавшуюся функцию в РНР только потому, что она присутствует в этом языке и кем-то рекомендована. Если, конечно, вебразработчика интересует быстрота работы программы на PHP, равно как и скорость открытия страниц сайта в целом. Если в конкретной ситуации язык дает несколько возможностей для решения одной и той же задачи (т.е. если возможно применить разные функции), то, чтобы сайт функционировал наиболее быстро, следует, увы, тестировать, как работает каждая из функций и выбирать наиболее оптимальную. Да, вывод этот, конечно, банальный. Однако, скорость работы функций РНР в маннуалах не прописана. Да и на форумах компьютерных этот вопрос, зачастую, как-то обходят стороной. Работает мол (как-то там), да и ладно. Так что выход здесь один: практическое тестирование функциональности/скорости. Не обращая внимания на маннуалы.

