Не работает split php
Создание сайтов на Django
Данный курс научит Вас создавать сайты на очень мощном фреймворке – Django. Курс состоит из 9 разделов, в которых Вы с нуля освоите данный фреймворк на примере создания полноценного Интернет-магазина.
В рамках многочисленных упражнений Вы так же создадите свой собственный сайт, что даст Вам ту необходимую практику для закрепления материала, а также полноценную серьёзную работу для своего портфолио.
Помимо самого курса Вас ждёт ещё и бесплатный ценный Бонус: «Unit-тестирование сайта на Django». В этом Бонусе Вы узнаете, как можно написать автоматические тесты для проекта на Django. Это позволит находить оперативно ошибки, а также даст возможность в будущем добавлять новый функционал, не боясь что-то сломать в старом.
Подпишитесь на мой канал на YouTube, где я регулярно публикую новые видео.
Подписаться
Подписавшись по E-mail, Вы будете получать уведомления о новых статьях.
Подписаться
Добавляйтесь ко мне в друзья ВКонтакте! Отзывы о сайте и обо мне оставляйте в моей группе.
Мой аккаунт Моя группа
Зачем Вы изучаете программирование/создание сайтов?
Написание лайфхаков на Python для начинающих
Данный курс покажет Вам, как можно автоматизировать рутинные задачи с помощью Python. В курсе Вас ждёт несколько примеров и все исходники.
Чтобы получить Видеокурс,
заполните форму
11 шагов к созданию своей Web-студии
— Вы узнаете главное отличие богатых от бедных.
— Вы увидите разоблачения множества мифов об успешности и о бизнесе.
— Вы получите свой личный финансовый план прямо на семинаре.
— Мы разберём 11 шагов к созданию своей успешной Web-студии.
— Я расскажу о своих личных историях: об успешных и неуспешных бизнесах. Это мой многолетний опыт, которым я поделюсь с Вами.
Источник
split
split — Разбиение строки на массив по регулярному выражению
Эта функция объявлена УСТАРЕВШЕЙ в PHP 5.3.0, и УДАЛЕНА PHP 7.0.0.
Есть следующие альтернативы:
Описание
Разбивает строку string на массив по регулярному выражению.
Список параметров
Регулярное выражение, чувствительное к регистру.
Если необходимо разбить строку по символам, являющимся специальными для регулярных выражений, их следует экранировать. Если вам кажется, что split() (или любая другая функция, работающая с регулярными выражениями) ведёт себя неожиданно, пожалуйста, прочтите файл regex.7 , расположенный в поддиректории regex/ дистрибутива PHP. Он сохранён в формате manpage, поэтому для удобства чтения используйте команду man /usr/local/src/regex/regex.7.
Если указан параметр limit , возвращаемый массив будет содержать максимум limit элементов, причём последний элемент будет включать всю оставшуюся часть строки string .
Возвращаемые значения
Возвращает массив строк, каждая из которых является строкой, образованной разбиением строки string чувствительным к регистру регулярным выражением pattern .
Если pattern встречается n раз, результирующий массив будет содержать n +1 элементов. Например, если pattern в строке отсутствует, будет возвращён массив, содержащий 1 элемент. Само собой, это также верно в случае, когда string является пустой строкой. В случае ошибки split() возвращает false .
Примеры
Пример #1 Пример использования split()
Получаем первые четыре поля строки из /etc/passwd :
Пример #2 Пример использования split()
Распознаем дату, отформатированную с использованием слешей, точек или дефисов:
Примечания
Функция split() является устаревшей начиная с PHP 5.3.0. Предлагается использовать вместо неё функцию preg_split() . В случае, когда нет необходимости использовать регулярные выражения, эффективнее использовать explode() , которая не использует дополнительные ресурсы для разбора регулярного выражения.
Пользователям, которым необходимо эмулировать поведение @chars = split(», $str) из Perl, следует обратиться к примерам для preg_split() или str_split() .
Смотрите также
- preg_split() — Разбивает строку по регулярному выражению
- spliti() — Разбивает строку в массив с помощью регулярного выражения без учёта регистра
- str_split() — Преобразует строку в массив
- explode() — Разбивает строку с помощью разделителя
- implode() — Объединяет элементы массива в строку
- chunk_split() — Разбивает строку на фрагменты
- wordwrap() — Переносит строку по указанному количеству символов
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:
function getCSVValues ( $string , $separator = «,» )
<
$elements = explode ( $separator , $string );
for ( $i = 0 ; $i count ( $elements ); $i ++) <
$nquotes = substr_count ( $elements [ $i ], ‘»‘ );
if ( $nquotes % 2 == 1 ) <
for ( $j = $i + 1 ; $j count ( $elements ); $j ++) <
if ( substr_count ( $elements [ $j ], ‘»‘ ) % 2 == 1 ) < // Look for an odd-number of quotes
// Put the quoted string’s pieces back together again
array_splice ( $elements , $i , $j — $i + 1 ,
implode ( $separator , array_slice ( $elements , $i , $j — $i + 1 )));
break;
>
>
>
if ( $nquotes > 0 ) <
// Remove first and last quotes, then merge pairs of quotes
$qstr =& $elements [ $i ];
$qstr = substr_replace ( $qstr , » , strpos ( $qstr , ‘»‘ ), 1 );
$qstr = substr_replace ( $qstr , » , strrpos ( $qstr , ‘»‘ ), 1 );
$qstr = str_replace ( ‘»»‘ , ‘»‘ , $qstr );
>
>
return $elements ;
>
?>
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:
function quotesplit($s, $splitter=’,’)
<
//First step is to split it up into the bits that are surrounded by quotes and the bits that aren’t. Adding the delimiter to the ends simplifies the logic further down
$getstrings = split(‘\»‘, $splitter.$s.$splitter);
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
while (list($arg, $val) = each($getstrings))
<
if ($instring==1)
<
//Add the whole string, untouched to the result array.
$result[] = $val;
$instring = 0;
>
else
<
//Break up the string according to the delimiter character
//Each string has extraneous delimiters around it (inc the ones we added above), so they need to be stripped off
$temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen ) );
while(list($iarg, $ival) = each($temparray))
<
$result[] = trim($ival);
>
$instring = 1;
>
>
return $result;
>
strange things happen with split
this didn’t work
$vontag $vonmonat were empty strings
function ckdate ( $fromdate = «01.01» , $todate = «31.12» )
<
$nowyear = date ( «Y» );
list ( $vontag , $vonmonat ) = split ( ‘.’ , $fromdate ); // $vondatum = » $nowyear — $vonmonat — $vontag » ;
list ( $bistag , $bismonat ) = split ( ‘.’ , $todate ); // $bisdatum = » $nowyear — $bismonat — $bistag » ;
$von = strtotime ( $vondatum );
$bis = strtotime ( $bisdatum );
$now = time ();
if (( $now $bis ) and ( $now >= $von ))
<
return TRUE ;
>
else
<
return FALSE ;
>
>
?>
however this one worked perfectly
function ckdate ( $fromdate = «01.01» , $todate = «31.12» )
<
$nowyear = date ( «Y» );
list ( $vontag , $vonmonat ) = split ( ‘[.]’ , $fromdate ); // $vondatum = » $nowyear — $vonmonat — $vontag » ;
list ( $bistag , $bismonat ) = split ( ‘[.]’ , $todate ); // $bisdatum = » $nowyear — $bismonat — $bistag » ;
$von = strtotime ( $vondatum );
$bis = strtotime ( $bisdatum );
$now = time ();
if (( $now $bis ) and ( $now >= $von ))
<
return TRUE ;
>
else
<
return FALSE ;
>
>
?>
btw this fn checks if $now if between $fromdate and $todate
use it if you like
If you want to use split to check on line feeds (\n), the following won’t work:
$line = split(«\n», $input_several_lines_long);
You really have to do this instead, notice the second slash:
$line = split(«\\n», $input_several_lines_long);
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
in this situation.
I’ve try using split function.
= «2�12» ;
$valore = split ( «[�]» , $ferro );
echo $ferro . «
» ;
echo «p1-» . $valore [ 0 ]. «
» ;
echo «p2-» . $valore [ 1 ]. «
» ;
echo «p3-» . $valore [ 2 ]. «
» ;
$ferro = «2d12» ;
$valore = split ( «[d]» , $ferro );
echo $ferro . «
» ;
echo «p1-» . $valore [ 0 ]. «
» ;
echo «p2-» . $valore [ 1 ]. «
» ;
echo «p3-» . $valore [ 2 ]. «
» ;
?>
This return:
============
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:
$line = split(«\n», $input_several_lines_long);
You really have to do this instead, notice the second slash:
$line = split(«/\n», $input_several_lines_long);
Took me a little while to figure to do
The example from ramkumar rajendran did not work.
$line = split(«/\n», $input_several_lines_long);
I do not know why this does not work for me.
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:
$line = «12|3|Fred»;
list ($msgid, $msgref, $msgtopic)=split(‘|’, $line);
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:
$line = «12|3|Fred»;
list ($msgid, $msgref, $msgtopic)=split(‘\|’, $line);
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:
Added another —length; into the if statement below:
// 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.
function quotesplit( $splitter=’,’, $s )
<
//First step is to split it up into the bits that are surrounded by quotes
//and the bits that aren’t. Adding the delimiter to the ends simplifies
//the logic further down
$getstrings = explode(‘»‘, $splitter.$s.$splitter);
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
while (list($arg, $val) = each($getstrings))
<
if ($instring==1)
<
//Add the whole string, untouched to the previous value in the array
$result[count($result)-1] = $result[count($result)-1].$val;
$instring = 0;
>
else
<
//Break up the string according to the delimiter character
//Each string has extraneous delimiters around it (inc the ones we added
//above), so they need to be stripped off
$temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen+1 ) );
while(list($iarg, $ival) = each($temparray))
<
$result[] = trim($ival);
>
$instring = 1;
>
>
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.
The following code will mimick the explode functionality: explode( » «, $s ); The difference, of course, is that the split method takes a regular expression instead of a string.
$s = «Split this sentence by spaces»;
$words = split(«[ ]+», $s);
print_r($words);
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. 🙂
$BRCount = substr_count ( $Message , ‘
‘ );
if ( $BRCount $MaxNewLines )
$MaxNewLines = $BRCount ;
else if( $BRCount == 0 )
$MaxNewLines = 1 ;
$Message = str_replace ( chr ( 13 ), «
» , $Message );
$MessageArray = split ( «
» , $Message , $MaxNewLines );
$Message = «» ; $u = 0 ;
do <
$Message .= $MessageArray [ $u ]. ‘
‘ ;
$u ++;
> while( $u $MaxNewLines — 1 ));
$Message .= str_replace ( «
» , » » , $MessageArray [ $u ]);
?>
Those of you trying to use split for CSV, it won’t always work as expected. Instead, try using a simple stack method:
/**
* Create a 2D array from a CSV string
*
* @param mixed $data 2D array
* @param string $delimiter Field delimiter
* @param string $enclosure Field enclosure
* @param string $newline Line seperator
* @return
*/
function parse ( $data , $delimiter = ‘,’ , $enclosure = ‘»‘ , $newline = «\n» ) <
$pos = $last_pos = — 1 ;
$end = strlen ( $data );
$row = 0 ;
$quote_open = false ;
$trim_quote = false ;
// Create a continuous loop
for ( $i = — 1 ;; ++ $i ) <
++ $pos ;
// Get the positions
$comma_pos = strpos ( $data , $delimiter , $pos );
$quote_pos = strpos ( $data , $enclosure , $pos );
$newline_pos = strpos ( $data , $newline , $pos );
// Which one comes first?
$pos = min (( $comma_pos === false ) ? $end : $comma_pos , ( $quote_pos === false ) ? $end : $quote_pos , ( $newline_pos === false ) ? $end : $newline_pos );
// Cache it
$char = (isset( $data [ $pos ])) ? $data [ $pos ] : null ;
$done = ( $pos == $end );
// It it a special character?
if ( $done || $char == $delimiter || $char == $newline )<
// Ignore it as we’re still in a quote
if ( $quote_open && ! $done ) <
continue;
>
$length = $pos — ++ $last_pos ;
// Is the last thing a quote?
if ( $trim_quote ) <
// Well then get rid of it
— $length ;
>
// Get all the contents of this column
$return [ $row ][] = ( $length > 0 ) ? str_replace ( $enclosure . $enclosure , $enclosure , substr ( $data , $last_pos , $length )) : » ;
// And we’re done
if ( $done ) <
break;
>
// Save the last position
$last_pos = $pos ;
// Next row?
if ( $char == $newline ) <
++ $row ;
>
$trim_quote = false ;
>
// Our quote?
else if ( $char == $enclosure )<
// Toggle it
if ( $quote_open == false ) <
// It’s an opening quote
$quote_open = true ;
$trim_quote = false ;
// Trim this opening quote?
if ( $last_pos + 1 == $pos ) <
++ $last_pos ;
>
>
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.
function quotesplit( $splitter=’,’, $s, $restore_quotes=0 )
<
//First step is to split it up into the bits that are surrounded by quotes
//and the bits that aren’t. Adding the delimiter to the ends simplifies
//the logic further down
$getstrings = explode(‘»‘, $splitter.$s.$splitter);
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
while (list($arg, $val) = each($getstrings))
<
if ($instring==1)
<
if( $restore_quotes )
<
//Add the whole string, untouched to the previous value in the array
$result[count($result)-1] = $result[count($result)-1].'»‘.$val.'»‘;
> else <
//Add the whole string, untouched to the array
$result[] = $val;
>
$instring = 0;
>
else
<
//Break up the string according to the delimiter character
//Each string has extraneous delimiters around it (inc the ones we added
//above), so they need to be stripped off
$temparray = split($splitter, substr($val, $delimlen, strlen($val)-$delimlen-$delimlen+1 ) );
while(list($iarg, $ival) = each($temparray))
<
$result[] = trim($ival);
>
$instring = 1;
>
>
// Split a string into words on boundaries of one or more spaces, tabs or new-lines
$s = «Please cut \t me \n in pieces»;
$words = split(«[\n\r\t ]+», $s);
print_r($words);
Источник