php cut string by length
PHP: substr и мощные альтернативы, чтобы вырезать часть строки
Поговорим о том, как обрезать строку в PHP. Функция substr в предназначена для получения части строки. Она выделяет подстроку из переданной строки и возвращает её. Для этого нужно указать строку, порядковый номер символа, начиная с которого нужно вырезать строку, порядковый номер символа, до которого мы верезаем подстроку.
Обратите внимание, что substr неправильно работает с многобайтовыми кодировками, поэтому мы будем использовать mb_substr, которая работает с ними корректно. Об этой проблеме немного ниже.
Теперь перейдем к примерам.
Получаем строку начиная с определенного символа
Мы вырезали первые 8 символов из строки, содержащей URL адрес.
Получаем определенное количество символов
Теперь давайте вырежем еще и «/admin/» в конце.
Мы бы могли сделать это указав количество символов, которое нужно взять, оно равно количеству символов в домене, их 11
Вырезаем символы с конца
Что если мы не знаем количества символов в домене, но знаем что нужно вырезать строку «/admin/», длина которой составляет 7 символов? Иными словами нам нужно вырезать с конца.
В таком случае нужно указать отрицательное число:
Получаем несколько последних символов
Что если нам нужно вернуть наоборот только 7 последних символов? Тогда код будет следующим:
Получаем первый символ строки
Получаем последний символ строки
Получение подстроки по регулярному выражению
Проблема при работе с многобайтовыми кодировками.
Рассмотрим такой пример:
Что случилось? Почему в первом случае, где мы использовали mb_substr все сработало хорошо, а во втором случае вернулся какой-то битый символ?
Дело в том, что в UTF-8 кириллица кодируется 2 байтам, вместо одного. substr считает, что символ равен байту и поэтому вырезает 3 байта с начала. Таким образом она вырезала букву «П», и только половину буквы «Р». В общем вы поняли: всегда используйте mb_substr когда работаете с текстом, который потенциально может содержать многобайтовые символы.
Продвинутая работа со строками
Если вы часто работаете со строками, вам пригодится это расширение: symfony/string
С его помощью вы сможете легко вырезать строки. Взгляните на несколько примеров:
Cut A String To A Specified Length With PHP
Cutting a string to a specified length is accomplished with the substr() function. For example, the following string variable, which we will cut to a maximum of 30 characters.
The substr() function has three parameters. The first is the string, the second is where to start cutting from and the third is the amount of characters to cut to. So to cut to 30 characters we would use the following.
The string variable is now set to the following.
This example highlights the major problem with this function in that it will take no notice of the words in a string. The solution is to create a new function that will avoid cutting words apart when cutting a string by a number of characters.
This function splits the string into words and then joins them back together again one by one. The good thing is that if there is a word that would make the string longer than the required number of characters it doesn’t include the word. The function can be called like this.
This produces the following output.
Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK. Phil is currently a Developer at Code Enigma.
Comments
Save a bit of processor time by doing this:
Thanks for this, it saved my skin
// UTF8 compatibility » add «mb_» before «strlen» for UTF8 compatibility
This is so coolaborative, then I show an more easy way:
If a call a function is better make a condition first, like that:
Как с помощью различных функций PHP обрезать строку?
В этой статье мы рассмотрим несколько различных способов в PHP обрезать строку на определенное количество слов и символов. Большая часть функций, описанных в этой статье, используется, чтобы продемонстрировать возможности PHP для работы со строками.
В нашем примере мы также используем вторую строку из 55 символов, чтобы вы могли проверить возвращаемый результат на более короткой строке.
mb_strimwidth()
Функция рассматривает свободное пространство как символ. Но это значит, что между последним усеченным символом и конечным символом многоточием будет размещаться пробел. Вы можете обрезать строку без конечного символа, а затем добавить его отдельно. Посмотрите на следующий пример:
Приведенный выше код добавляет многоточие не зависимо от того, была ли PHP обрезана строка до символа или нет. Чтобы исправить это, мы будем рассчитывать длину строки, и только после этого добавлять многоточие, если исходная строка действительно должна обрезаться. Например:
При отправке сообщений в Twitter и на другие ресурсы, где символы чувствительны к регистру, каждый символ имеет значение… и эта функция в ряде случаев сэкономит вам один пробел!
mb_substr()
mb_substr(), substr() и mb_strcut()
Если вы выводите PHP обрезанную часть строки до ближайшего слова на основе количества символов ( но без конечного многоточия ), используйте следующий код:
preg_match()
Описание функции
Строка 7
Строка 9
Строки 10, 11, и 12
Затем мы возвращаем либо усеченную строку, либо исходную строку, если она меньше заданной длины усечения.
strrpos()
wordwrap()
Определение для параметра cut значения true означает, что строка всегда оборачивается до или на указанном символе.
str-split()
Функция str-split() может быть использована в приведенной выше функции для преобразования строки в массив. str-split () не разбивает строку до целого слова. С ее помощью PHP обрезает последний символ в строке ровно до 120 знаков.
Усечение по заданному количеству слов
strtok()
Обрезка слов в WordPress
Заключение
Скачать примеры
substr
(PHP 4, PHP 5, PHP 7, PHP 8)
substr — Возвращает подстроку
Описание
Список параметров
Если string меньше offset символов, будет возвращена пустая строка.
Пример #1 Использование отрицательного параметра offset
Если length положительный, возвращаемая строка будет не длиннее length символов, начиная с параметра offset (в зависимости от длины string ).
Если параметр length опущен, то будет возвращена подстрока, начинающаяся с позиции, указанной параметром offset и длящейся до конца строки.
Пример #2 Использование отрицательного параметра length
Возвращаемые значения
Возвращает извлечённую часть параметра string или пустую строку.
Список изменений
Примеры
Пример #3 Базовое использование substr()
Пример #4 substr() и приведение типов
class apple <
public function __toString () <
return «green» ;
>
>
Результат выполнения данного примера:
Пример #5 Недопустимый диапазон символов
Результат выполнения данного примера в PHP 8:
Результат выполнения данного примера в PHP 7:
Смотрите также
User Contributed Notes 36 notes
For getting a substring of UTF-8 characters, I highly recommend mb_substr
may be by following functions will be easier to extract the needed sub parts from a string:
Coming to PHP from classic ASP I am used to the Left() and Right() functions built into ASP so I did a quick PHPversion. hope these help someone else making the switch
Shortens the filename and its expansion has seen.
### SUB STRING BY WORD USING substr() and strpos() #####
### THIS SCRIPT WILL RETURN PART OF STRING WITHOUT WORD BREAK ###
Drop extensions of a file (even from a file location string)
= «c:/some dir/abc defg. hi.jklmn» ;
?>
output: c:/some dir/abc defg. hi
Hope it may help somebody like me.. (^_^)
PS:I’m sorry my english is too poor. 🙁
If you want to have a string BETWEEN two strings, just use this function:
$string = «123456789» ;
$a = «12» ;
$b = «9» ;
If you need to parse utf-8 strings char by char, try this one:
Be aware of a slight inconsistency between substr and mb_substr
mb_substr(«», 4); returns empty string
substr(«», 4); returns boolean false
tested in PHP 7.1.11 (Fedora 26) and PHP 5.4.16 (CentOS 7.4)
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:
(substr) 3.24
(direct access) 11.49
(strstr) 4.96
(With standard deviations 0.01, 0.02 and 0.04)
THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers.
For example when using ip2country, or eliminating same range of ip addresses from your website 😀
$min = ip2no ( «10.11.1.0» );
$max = ip2no ( «111.11.1.0» );
$visitor = ip2no ( «105.1.20.200» );
I created some functions for entity-safe splitting+lengthcounting:
I needed a function like lpad from oracle, or right from SQL
then I use this code :
Just a little function to cut a string by the wanted amount. Works in both directions.
Anyone coming from the Python world will be accustomed to making substrings by using a «slice index» on a string. The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third «step» argument.)
The output from the examples:
c
cd
cdefg
abcd
abcd
efg
I have developed a function with a similar outcome to jay’s
Checks if the last character is or isnt a space. (does it the normal way if it is)
It explodes the string into an array of seperate works, the effect is. it chops off anything after and including the last space.
I needed to cut a string after x chars at a html converted utf-8 text (for example Japanese text like 嬰謰弰脰欰罏).
The problem was, the different length of the signs, so I wrote the following function to handle that.
Perhaps it helps.
Using a 0 as the last parameter for substr().
[English]
I created python similar accesing list or string with php substr & strrev functions.
About of pattern structures
[start:stop:step]
?>
Using this is similar to simple substr.
str_split
str_split — Преобразует строку в массив
Описание
Преобразует строку в массив.
Список параметров
Максимальная длина фрагмента.
Возвращаемые значения
Примеры
Пример #1 Пример использования str_split()
Результат выполнения данного примера:
Примечания
Функция str_split() производит разбивку по байтам, а не по символам, в случае использования строк в многобайтных кодировках.
Смотрите также
User Contributed Notes 40 notes
A proper unicode string split;
print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));
A new version of «str_split_unicode» prev.
heres my version for php4 and below
The manual don’t says what is returned when you parse a different type of variable.
This is the example:
= «Long» ; // More than 1 char
$str2 = «x» ; // Only 1 char
$str3 = «» ; // Empty String
$str4 = 34 ; // Integer
$str5 = 3.4 ; // Float
$str6 = true ; // Bool
$str7 = null ; // Null
I noticed in the post below me that his function would return an array with an empty key at the end.
So here is just a little fix for it.
I needed a function that could split a string from the end with any left over chunk being at the beginning of the array (the beginning of the string).
The documentation fails to mention what happens when the string length does not divide evenly with the chunk size. Not sure if the same behavior for all versions of PHP so I offer the following code to determine this for your installation. On mine [version 5.2.17], the last chunk is an array the length of the remaining chars.
The very handy str_split() was introduced in PHP 5, but a lot of us are still forced to use PHP 4 at our host servers. And I am sure a lot of beginners have looked or are looking for a function to accomplish what str_split() does.
Taking advantge of the fact that strings are ‘arrays’ I wrote this tiny but useful e-mail cloaker in PHP, which guarantees functionality even if JavaScript is disabled in the client’s browser. Watch how I make up for the lack of str_split() in PHP 4.3.10.
// The result is an email address in HTML entities which, I hope most email address harvesters can’t read.
>
print cloakEmail ( ‘someone@nokikon.com’ );
?>
###### THE CODE ABOVE WITHOUT COMMENTS ######
It’s mentioned in the Return Values section above («If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element»), but note that an input of empty string will return array(1) < [0]=>string(0) «» >. Interestingly an input of NULL will also return array(1) < [0]=>string(0) «» >.
revised function from tatsudoshi
The previous suggestion is almost correct (and will only working for strlen=1. The working PHP4 function is:
Even shorter version:
//place each character (or group of) of the
string into and array
the fastast way (that fits my needs) to replace str_split() in php 4 i found is this: