php разделить строку на две части
PHP метод explode для разбиения строки с тремя примерами
Метод PHP explode используется для разбиения строки на заданное число подстрок.
Синтаксис метода
Пример использования PHP метода explode :
Пример использования explode для разбиения номера телефона
В этом примере мы объявили строковую переменную и присвоили ей номер телефона следующего формата:
После этого применили метод explode для разбиения строки с помощью дефиса ( тире ) в качестве разделителя. Возвращенный массив строк присвоили массиву.
Затем использовали цикл fогеасh для отображения значений элементов массива, которые являются подстроками номера телефона. Поскольку параметр limit не указан, весь номер телефона будет разбит на три подстроки:
Посмотреть демо и код
Пример с пробелом в качестве разделителя
В этом примере PHP explode переноса строки использован пробел в качестве разделителя. Для примера возьмем это строку:
This is explode tutorial that enables string split in PHP.
Наконец, применили функцию count() для вывода количества подстрок в массиве:
Посмотреть демо и код
Пример с параметром limit
Это пример, описанный выше, за исключением того, что здесь мы использовали параметр limit для указания количества разбиений в строке. Ниже показана строка, которая была использована:
This is explode tutorial that enables string split in PHP.
В PHP explode примере, когда мы использовали пробел в качестве разделителя, было возвращено всего 10 подстрок. На этот раз с помощью параметра limit было определено 5 разбиений:
Посмотреть демо и код
Для чего нужен метод explode
Метод explode ( PHP split ) используется для разбиения заданной строки. Допустим, что веб-форма принимает телефонный номер с кодом страны и области в следующем формате:
Нам нужно отделить код страны и области, которые разделены дефисом. Для разбиения телефонного номера можно воспользоваться explode с разделителем дефисом ( тире ) после принятия номера в качестве входного параметра.
Поскольку explode возвращает массив подстрок, метод explode разобьет номер в следующий массив элементов:
Как использовать функцию PHP explode
В функции PHP explode можно указать три параметра. Последний из них — необязательный, так как указывать количество разбиений ( максимальное количество подстрок ) необязательно.
Описание каждого параметра:
Если в explode array PHP аргумент limit является положительным, возвращаемый массив будет содержать максимальное количество элементов, при этом последний элемент будет содержать остаток строки.
Также можно использовать отрицательное значение. В этом случае все подстроки ( кроме последней ) будут возвращены.
Поскольку explode возвращает массив подстрок, то можно присвоить его массиву. После применения метода можно использовать цикл fогеаch, чтобы перебрать массив элементов, как показано в приведенных выше примерах.
Примечание: Также можно использовать метод str_split для преобразования строки в массив.
Пожалуйста, оставляйте свои мнения по текущей теме статьи. Мы крайне благодарны вам за ваши комментарии, подписки, отклики, дизлайки, лайки!
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:
split
split — Разбиение строки на массив по регулярному выражению
Эта функция объявлена УСТАРЕВШЕЙ в PHP 5.3.0, и УДАЛЕНА PHP 7.0.0.
Есть следующие альтернативы:
Описание
Разбивает строку string на массив по регулярному выражению.
Список параметров
Регулярное выражение, чувствительное к регистру.
Возвращаемые значения
Примеры
Пример #1 Пример использования split()
Получаем первые четыре поля строки из /etc/passwd :
Пример #2 Пример использования split()
Распознаем дату, отформатированную с использованием слешей, точек или дефисов:
Примечания
Смотрите также
User Contributed Notes 25 notes
In response to the getCSVValues() function posted by justin at cam dot org, my testing indicates that it has a problem with a CSV string like this:
To fix this, I changed the second substr_count to look for an odd number of quotes, as opposed to any quotes at all:
moritz’s quotesplit didn’t work for me. It seemed to split on a comma even though it was between a pair of quotes. However, this did work:
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
strange things happen with split
If you want to use split to check on line feeds (\n), the following won’t work:
Took me a little while to figure out.
It’s evident but not mentioned in the documentation that using asterisks is more restricted than in a normal regular expression.
for exaple you cannot say:
because what if there’s no «;» separator?(which is covered by this regular expression)
so you have to use at least
I’ve try using split function.
I use charset UTF-8. When I use char � the split function ad an empty string between «2» and «12». Why?
UTF-8 charset codes some characters (like the «�» character) into two bytes. In fact the regular expresion «[�]» contains 4 bytes (4 non-unicode characters). To demonstrate the real situation I wrote following example:
In answer to gwyne at gmx dot net, dec 1, 2002:
For split(), when using a backslash as the delimiter, you have to *double escape* the backslash.
A correction to a earlier note
If you want to use split to check on line feeds (\n), the following won’t work:
Took me a little while to figure to do
The following has worked for me to get a maximum of 2 array parts separated by the first new line (independant if saved under UNIX or WINDOWS):
$line = preg_split(‘/[\n\r]+/’,$input_several_lines_long,2);
Also empty lines are not considered here.
[Ed. note: Close. The pipe *is* an operator in PHP, but
the reason this fails is because it’s also an operator
in the regex syntax. The distinction here is important
since a PHP operator inside a string is just a character.]
The reason your code:
didn’t work is because the «|» symbol is an operator in PHP. If you want to use the pipe symbol as a delimiter you must excape it with a back slash, «\|». You code should look like this:
split() doesn’t like NUL characters within the string, it treats the first one it meets as the end of the string, so if you have data you want to split that can contain a NUL character you’ll need to convert it into something else first, eg:
Thank you Dave for your code below. Here is one change I made to avoid a redundant quote at the end of some lines (at least when I used excel:
// Is the last thing a quote?
if ($trim_quote) <
// Well then get rid of it
—$length;
// ADD TO FIX extra quote
—$length;
>
wchris’s quotesplit assumes that anything that is quoted must also be a complete delimiter-seperated entry by itself. This version does not. It also uses split’s argument order.
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
Though this is obvious, the manual is a bit incorrect when claiming that the return will always be 1+number of time the split pattern occures. If the split pattern is the first part of the string, the return will still be 1. E.g.
$a = split(«zz,» «zzxsj.com»);
count($a);
The return of this can not in anyway be seperated from the return where the split pattern is not found.
I’d like to correct myself, I found that after testing my last solution it will create 5 lines no matter what. So I added this to make sure that it only displays 5 if there are five newlines. 🙂
Those of you trying to use split for CSV, it won’t always work as expected. Instead, try using a simple stack method:
>
else <
// It’s a closing quote
$quote_open = false ;
// Trim the last quote?
$trim_quote = true ;
>
?>
This *should* work for any valid CSV string, regardless of what it contains inside its quotes (using RFC 4180). It should also be faster than most of the others I’ve seen. It’s very simple in concept, and thoroughly commented.
If you need to do a split on a period make sure you escape the period out..
$ext_arr = split(«\.»,»something.jpg»);
. because
$ext_arr = split(«.»,»something.jpg»); won’t work properly.
Actually, this version is better than the last I submitted. The goal here is to be able to engage in *multiple* delimeter removal passes; for all but the last pass, set the third value to «1», and everything should go well.
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
Разбиение и объединение строк в PHP
Для разбиения строки на элементы используется функция explode(), которая принимает два параметра: строку, которую необходимо разбить и разделитель. Рассмотрим функцию explode() сразу на примере:
В данном примере, мы создаём массив, элементами которого становятся «Lexus«, «Smirnov«, «40«. То есть мы, учитывая разделитель «/«, разбили эту строку на несколько и записали их в массив. Существует так же и операция разбиение строки на элементы и мгновенная запись их в переменные:
То есть в данном примере, мы создали три переменные, в каждую из которых записали соответствующее значение.
Теперь о применении данной функции. В своё время я реализовывал задачу поиска по сайту. И мне нужно было сформировать из GET-запроса, полученного из формы, запрос к базе данных, чтобы извлечь оттуда подходящие записи. Проблема была в том, что ведь могут искать несколько слов сразу, например, «создать сайт быстро«. И нужно вывести все материалы со словами «создать«, либо «сайт«, либо «быстро«. И мне приходилось использовать функцию explode(), а в качестве разделителя брался пробел. А уже затем я формировал запрос к базе данных (разумеется, с количеством OR зависящем от количества слов, либо AND, если пользователь потребовал вхождение всех слов) и извлекал подходящие записи из таблицы базы данных. Вообще, задача была на порядок тяжелее, но тут я привёл Вам её кусок, чтобы Вы поняли, что бывают ситуации, когда без этой функции очень трудно работать.
Для объединения строк в PHP имеется функция implode(), которая принимает тоже два параметра: разделитель и массив:
В результате получится строка: «15.10.1985«. Думаю, что здесь всё прозрачно.
Вот и всё, что касается разбиения и объединения строк в PHP.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 19 ):
в функции explode(‘http://myrusakov.ru/’, «Lexus/Smirnov/40»); вместо знака / отображет ссылку на твой сайт.
Спасибо большое! Уже подправил.
Надо проверять не количество, а сами элементы. А слеш действительно добавит новый элемент, который будет пустой строкой.
Я правильно понимаю, что нужно в цикле for перебирать все элементы и функцией isset проверять их наличие? А как же мне проверить их общее количество? Соответствие количества главнее.
Не isset(), а просто значение. И да, через цикл.
Михаил, добрый день! Я правильно вас понял if ($hum1[$i]== 0)?
Михаил, спасибо! Все получилось! Подскажите, каким образом можно передать информацию из php в html? Читать ваши уроки по порядку не получается (много забывается сразу), поэтому изучаю php по мере решения задач. Спасибо!
Ну так я и выполняю упражнения, только свои. У вас на сайте, к сожалению, не нашел упражнений. Или я чего то не увидел?
На сайте упражнений нет, они есть в этом курсе: http://srs.myrusakov.ru/kurs
А мне кажется это хорошая идея сделать на сайте тесты для новичков примерно такие же как в курсе. почему вы не отреогировали?
Михаил, добрый день! Я немного неправильно сформулировал свой вопрос. Есть форма, которая передает данные в php. Там данные обрабатываются и выводятся на форму html. Мне нужно совместить две формы html в одну. Т.е. сверху ввожу, нажимаю «рассчитать» и снизу получаю ответ. Как передать информацию из php в ту же форму, из которой взяты первичные данные.
Раз хотите чтобы Вам именно в html выводилось, можете использовать javascript http://myrusakov.ru/javascript-post.html
А какие еще есть варианты? У меня блог на WP. Есть страничка, в которой поля для ввода данных. Есть возможность для вывода прямо на страницу?
Вы и html всё хотите оставить, и с javascript не хотите связываться? Ну уж извитите, таких простых решений не бывает.
Михаил, при чем тут «не хотите связываться»? Я просто узнаю у вас все возможные варианты. Вы специалист, я новичок. Мне кажется это нормально, когда человек интересуется всеми возможными вариантами! И никто не ждет готовых решений! Если не хотите отвечать, так не отвечайте. А уж если, сделали возможность задавать вопросы, то тогда отвечайте без сарказма. Это же диалог! Зачем же показывать свое превосходство?!
Функции для работы со строками
Для получения информации о более сложной обработке строк обратитесь к функциями 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