Php get and split

Splitting strings in PHP and get the last part [duplicate]

which works fine, except: If my input string does not contain any «-«, I must get the whole string, like from:

16 Answers 16

  • preg_split($pattern,$string) split strings within a given regex pattern
  • explode($pattern,$string) split strings within a given pattern
  • end($arr) get last array element
$strArray = explode('-',$str) $lastElement = end(explode('-', $strArray)); // or $lastElement = end(preg_split('/-/', $str)); 

Will return the last element of a — separated string.

And there’s a hardcore way to do this:

$str = '1-2-3-4-5'; echo substr($str, strrpos($str, '-') + 1); // | '--- get the last position of '-' and add 1(if don't substr will get '-' too) // '----- get the last piece of string after the last occurrence of '-' 

array_pop will remove last element from array and return the last element, end just return the last element. I think there’s no performance difference.

end(explode(‘-‘,$str)) gives this error: Strict (2048): Only variables should be passed by reference . This solves: stackoverflow.com/questions/4636166/…

$string = 'abc-123-xyz-789'; $exploded = explode('-', $string); echo end($exploded); 

This does not have the E_STRICT issue.

Just check whether or not the delimiting character exists, and either split or don’t:

if (strpos($potentiallyDelimitedString, '-') !== FALSE)

To satisfy the requirement that «it needs to be as fast as possible» I ran a benchmark against some possible solutions. Each solution had to satisfy this set of test cases.

$cases = [ 'aaa-zzz' => 'zzz', 'zzz' => 'zzz', '-zzz' => 'zzz', 'aaa-' => '', '' => '', 'aaa-bbb-ccc-ddd-eee-fff-zzz' => 'zzz', ]; 
function test_substr($str, $delimiter = '-') < $idx = strrpos($str, $delimiter); return $idx === false ? $str : substr($str, $idx + 1); >function test_end_index($str, $delimiter = '-') < $arr = explode($delimiter, $str); return $arr[count($arr) - 1]; >function test_end_explode($str, $delimiter = '-') < $arr = explode($delimiter, $str); return end($arr); >function test_end_preg_split($str, $pattern = '/-/')

Here are the results after each solution was run against the test cases 1,000,000 times:

test_substr : 1.706 sec test_end_index : 2.131 sec +0.425 sec +25% test_end_explode : 2.199 sec +0.493 sec +29% test_end_preg_split : 2.775 sec +1.069 sec +63% 

So turns out the fastest of these was using substr with strpos . Note that in this solution we must check strpos for false so we can return the full string (catering for the zzz case).

Источник

str_split

Если указан необязательный параметр length , возвращаемый массив будет разбит на фрагменты, каждый из которых будет иметь длину length , за исключением последнего фрагмента, который может быть короче, если строка делится неравномерно. По умолчанию параметр length равен 1 , то есть размер каждого фрагмента будет один байт.

Ошибки

Если параметр length меньше 1 , будет выброшена ошибка ValueError .

Список изменений

Версия Описание
8.2.0 Если параметр string не задан, теперь возвращается пустой массив ( array ). Ранее возвращался массив ( array ), содержащий одну пустую строку
8.0.0 Теперь если параметр length меньше 1 , будет выброшена ошибка ValueError ; ранее, вместо этого выдавалась ошибка уровня E_WARNING , а функция возвращала false .

Примеры

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

$arr1 = str_split ( $str );
$arr2 = str_split ( $str , 3 );

print_r ( $arr1 );
print_r ( $arr2 );

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

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d ) Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )

Примечания

Замечание:

Функция str_split() производит разбивку по байтам, а не по символам, в случае использования строк в многобайтных кодировках. Используйте функцию mb_str_split() , чтобы разбить строку на кодовые точки.

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

  • mb_str_split() — Если задана многобайтовая строка возвращает массив символов
  • chunk_split() — Разбивает строку на фрагменты
  • preg_split() — Разбивает строку по регулярному выражению
  • explode() — Разбивает строку с помощью разделителя
  • count_chars() — Возвращает информацию о символах, входящих в строку
  • str_word_count() — Возвращает информацию о словах, входящих в строку
  • for

User Contributed Notes 3 notes

The function str_split() is not ‘aware’ of words. Here is an adaptation of str_split() that is ‘word-aware’.

$array = str_split_word_aware (
‘In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.’ ,
32
);

/**
* This function is similar to str_split() but this function keeps words intact; it never splits through a word.
*
* @return array
*/
function str_split_word_aware ( string $string , int $maxLengthOfLine ): array
if ( $maxLengthOfLine <= 0 ) throw new RuntimeException ( sprintf ( 'The function %s() must have a max length of line at least greater than one' , __FUNCTION__ ));
>

$lines = [];
$words = explode ( ‘ ‘ , $string );

$currentLine = » ;
$lineAccumulator = » ;
foreach ( $words as $currentWord )

$currentWordWithSpace = sprintf ( ‘%s ‘ , $currentWord );
$lineAccumulator .= $currentWordWithSpace ;
if ( strlen ( $lineAccumulator ) < $maxLengthOfLine ) $currentLine = $lineAccumulator ;
continue;
>

// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace ;
$lineAccumulator = $currentWordWithSpace ;
>

if ( $currentLine !== » ) $lines [] = $currentLine ;
>

array( 5 ) [ 0 ]=> string ( 29 ) «In the beginning God created »
[ 1 ]=> string ( 30 ) «the heaven and the earth. And »
[ 2 ]=> string ( 28 ) «the earth was without form, »
[ 3 ]=> string ( 27 ) «and void; and darkness was »
[ 4 ]=> string ( 27 ) «upon the face of the deep. »
>

Источник

How to read multiple line from file and split it to array in php

You can use the php function file() to read the file line by line into an array. Then you have to loop through it and explode() by the white space.

$array = file('file.txt.'); foreach($array as $key => $line)

Firstly, initialize the array:

iterate the file line by line

$myArray contains your result

Firstly, this question explains how you read a file line by line in PHP. The top and bottom of it is:

$handle = fopen("inputfile.txt", "r"); if ($handle) < while (($line = fgets($handle)) !== false) < // process the line read. >> else < // error opening the file. >fclose($handle); 

Now in your case, you’ve got a structured line. Namely.

I would strongly, strongly argue against using a multi dimensional array for this. Instead, go for an OOP based solution. First, define a class.

Then you can create an array of Person objects.

Then cycle through each line and create a Person object.

while(($line = fgets($handle)) !== false)

Now you’ve got all the pieces of the puzzle, it’s up to you to put them all together!

@CharlotteDunois I just pulled from the other answer; didn’t want to replicate answers. I’ll upvote yours for using the later code. And the logic is, it’s much, much easier to conceptualise. It’s better to have a list of Person objects rather than an ugly, multi-dimensional array of values.

Well, you have to weigh the cost and use-factor of this class. The cost factor of an ‘ugly, multi-dimensional array’ (I think it’s better than using a class for something you wouldn’t need one) is much less than building a class. @christopher

But the next guy turning up will have a much easier time with $person->getName() then $array[$key][0][0] . It’s not just about the efficiency of the code. It’s about making maintainable code. Obviously it’s just two different approaches to development. @CharlotteDunois

Источник

Читайте также:  Сетевая работа в java
Оцените статью