php 不返回空字符串的爆炸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/64570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:21:33  来源:igfitidea点击:

Explode that doesn't return empty strings?

php

提问by Glenn Moss

PHP's explode function returns an array of strings split on some provided substring. It will return empty strings like this:

PHP 的explode 函数返回一个字符串数组,在某些提供的子字符串上拆分。它将像这样返回空字符串:

var_dump(explode('/', '1/2//3/'));
array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(0) ""
  [3]=>
  string(1) "3"
  [4]=>
  string(0) ""
}

Is there some different function or option or anything that would return everything exceptthe empty strings?

是否有一些不同的函数或选项或任何可以返回空字符串之外的所有内容的东西?

var_dump(different_explode('/', '1/2//3/'));
array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

回答by ceejayoz

Try preg_split.

试试preg_split

$exploded = preg_split('@/@', '1/2//3/', NULL, PREG_SPLIT_NO_EMPTY);

$exploded = preg_split('@/@', '1/2//3/', NULL, PREG_SPLIT_NO_EMPTY);

回答by Dave Gregory

array_filter will remove the blank fields, here is an example without the filter:

array_filter 将删除空白字段,这里是一个没有过滤器的例子:

print_r(explode('/', '1/2//3/'))

prints:

印刷:

Array
(
    [0] => 1
    [1] => 2
    [2] =>
    [3] => 3
    [4] =>
)

With the filter:

使用过滤器:

php> print_r(array_filter(explode('/', '1/2//3/')))

Prints:

印刷:

Array
(
    [0] => 1
    [1] => 2
    [3] => 3
)

You'll get all values that resolve to "false" filtered out.

您将过滤掉所有解析为“false”的值。

see http://uk.php.net/manual/en/function.array-filter.php

http://uk.php.net/manual/en/function.array-filter.php

回答by Glenn Moss

Just for variety:

只是为了多样性:

array_diff(explode('/', '1/2//3/'), array(''))

This also works, but does mess up the array indexes unlike preg_split. Some people might like it better than having to declare a callback function to use array_filter.

这也有效,但与 preg_split 不同,它会弄乱数组索引。有些人可能更喜欢它而不是必须声明一个回调函数来使用 array_filter。

回答by James Aylett

function not_empty_string($s) {
  return $s !== "";
}

array_filter(explode('/', '1/2//3/'), 'not_empty_string');

回答by Memochipan

I have used this in TYPO3, look at the $onlyNonEmptyValuesparameter:

我在TYPO3 中用过这个,看$onlyNonEmptyValues参数:

function trimExplode($delim, $string, $onlyNonEmptyValues=0){
    $temp = explode($delim,$string);
    $newtemp=array();
    while(list($key,$val)=each($temp))      {
        if (!$onlyNonEmptyValues || strcmp("",trim($val)))      {
            $newtemp[]=trim($val);
        }
    }
    reset($newtemp);
    return $newtemp;
}

It doesn't mess up the indexes:

它不会弄乱索引:

var_dump(trimExplode('/', '1/2//3/',1));

Result:

结果:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

回答by Garet Claborn

Here is a solution that should output a newly indexed array.

这是一个应该输出新索引数组的解决方案。

$result = array_deflate( explode( $delim, $array) );

function array_deflate( $arr, $emptyval='' ){
    $ret=[];
    for($i=0,$L=count($arr); $i<$L; ++$i)
        if($arr[$i] !== $emptyval) $ret[]=$arr[$i];
    return $ret;
}

While fairly similar to some other suggestion, this implementation has the benefit of generic use. For arrays with non-string elements, provide a typed empty value as the second argument.

虽然与其他一些建议非常相似,但此实现具有通用使用的好处。对于具有非字符串元素的数组,提供一个类型化的空值作为第二个参数。

array_deflate( $objArray, new stdClass() );

array_deflate( $objArray, new stdClass() );

array_deflate( $databaseArray, NULL );

array_deflate( $databaseArray, NULL );

array_deflate( $intArray, NULL );

array_deflate( $intArray, NULL );

array_deflate( $arrayArray, [] );

array_deflate( $arrayArray, [] );

array_deflate( $assocArrayArray, [''=>NULL] );

array_deflate( $assocArrayArray, [''=>NULL] );

array_deflate( $processedArray, new Exception('processing error') );

array_deflate( $processedArray, new Exception('processing error') );

.

.

.

.

.

.

With an optional filter argument..

使用可选的过滤器参数..

function array_deflate( $arr, $trigger='', $filter=NULL, $compare=NULL){
    $ret=[];
    if ($filter === NULL) $filter = function($el) { return $el; };
    if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };

    for($i=0,$L=count($arr); $i<$L; ++$i)
        if( !$compare(arr[$i],$trigger) ) $ret[]=$arr[$i];
        else $filter($arr[$i]);
    return $ret;
}

With usage..

随着使用..

function targetHandler($t){ /* .... */ }    
array_deflate( $haystack, $needle, targetHandler );

Turning array_deflate into a way of processing choice elements and removing them from your array. Also nicer is to turn the if statement into a comparison function that is also passed as an argument in case you get fancy.

将 array_deflate 变成一种处理选择元素并将它们从数组中删除的方法。更好的是将 if 语句转换为比较函数,如果您喜欢,该函数也作为参数传递。

array_inflatebeing the reverse, would take an extra array as the first parameter which matches are pushed to while non-matches are filtered.

array_inflate相反,将采用额外的数组作为第一个参数,匹配被推送到,同时过滤不匹配。

function array_inflate($dest,$src,$trigger='', $filter=NULL, $compare=NULL){
    if ($filter === NULL) $filter = function($el) { return $el; };
    if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };

    for($i=0,$L=count($src); $i<$L; ++$i)
        if( $compare(src[$i],$trigger) ) $dest[]=$src[$i];
        else $filter($src[$i]);
    return $dest;
}

With usage..

随着使用..

$smartppl=[];    
$smartppl=array_inflate( $smartppl,
                         $allppl,
                         (object)['intelligence'=>110],
                         cureStupid,
                         isSmart);

function isSmart($a,$threshold){
    if( isset($a->intellgence) )    //has intelligence?
        if( isset($threshold->intellgence) )    //has intelligence?
            if( $a->intelligence >= $threshold->intelligence )
                return true;
            else return INVALID_THRESHOLD; //error
        else return INVALID_TARGET; //error
    return false;
}

function cureStupid($person){
    $dangerous_chemical = selectNeurosteroid();
    applyNeurosteroid($person, $dangerous_chemical);

    if( isSmart($person,(object)['intelligence'=>110]) ) 
        return $person;
    else 
        lobotomize($person);

    return $person;
}

Thus providing an ideal algorithm for the world's educational problems. Aaand I'll stop there before I tweak this into something else..

从而为世界教育问题提供了理想的算法。Aaand 在我将其调整为其他内容之前,我会停在那里。

回答by Jeff

No regex overhead - should be reasonably efficient, strlen just counts the bytes

没有正则表达式开销 - 应该相当有效,strlen 只计算字节数

Drop the array_values() if you don't care about indexes

如果您不关心索引,请删除 array_values()

Make it into function explode_interesting( $array, $fix_index = 0 ) if you want

如果你愿意,可以把它变成函数explode_interesting( $array, $fix_index = 0 )

$interesting = array_values( 
                 array_filter(
                   explode('/', '/1//2//3///4/0/false' ),
                   function ($val) { return strlen($val); }
               ));

echo "<pre>", var_export( $interesting, true ), "</pre>";

enjoy, Jeff

享受,杰夫

回答by Adam Hopkinson

Regular expression solutions tend to be much slower than basic text replacement, so i'd replace double seperators with single seperators, trim the string of any whitespace and then use explode:

正则表达式解决方案往往比基本文本替换慢得多,所以我会用单分隔符替换双分隔符,修剪任何空格的字符串,然后使用爆炸:

// assuming $source = '1/2//3/';
$source = str_replace('//', '/', $source);
$source = trim($source);
$parts = explode('/', $source);

回答by Derek Kurth

I haven't tested the other suggestions here, but this works:

我还没有在这里测试其他建议,但这有效:

function different_explode($mypattern,$mystring){
    $array1 = explode($mypattern,$mystring);
    $retArray = Array();
    foreach($array1 as $myval){
        if($myval != ''){
            array_push($retArray,$myval);
        }
    }
    return $retArray;
}

回答by AntonioCS

Use this function to filter the output of the explode function

使用这个函数过滤explode函数的输出

  function filter_empty(&$arrayvar) {
        $newarray = array();
        foreach ($arrayvar as $k => $value)
            if ($value !== "")
                $newarray[$k] = $value;

        $arrayvar = $newarray;
    }