如何从数组中删除nbsp元素

时间:2019-03-02 14:19:54

标签: php arrays encoding

我的php数组中有包含&nbsp元素的元素,我尝试删除仅包含空格(&nbsp)的元素,因此我将其应用于我的数组:

        $steps = array_map( 'html_entity_decode', $steps);
        $steps = array_map('trim',$steps);
        $steps = array_filter($steps, 'strlen'); //(i try also array_filter($steps);

但是元素存在。

请问

1 个答案:

答案 0 :(得分:1)

尝试一下:

/**
 * Function to strip away a given string
 **/
function remove_nbsp($string){
    $string_to_remove = " ";
    return str_replace($string_to_remove, "", $string);
}

# Example data array
$steps = array("<p>step1</p>", "<p>step2</p>", "<p>step3</p>", "<p>&nbsp;</p>", "&nbsp;", "<p>&nbsp;</p>",  "<p>step4</p>");

$steps = array_map("strip_tags", $steps);
//Strip_tags() will remove the HTML tags
$steps = array_map("remove_nbsp", $steps);
//Our custom function will remove the &nbsp; character
$steps = array_filter($steps);
//Array_filter() will remove any blank array values

var_dump($steps);

/**
 * Output:
array(4) {
  [0]=>
  string(5) "step1"
  [1]=>
  string(5) "step2"
  [2]=>
  string(5) "step3"
  [6]=>
  string(5) "step4"
}
*/

您甚至可能发现做一个foreach()更容易:

foreach($steps as $dirty_step){
    if(!$clean_step = trim(str_replace("&nbsp;", "", strip_tags($dirty_step)))){
        //Ignore empty steps
        continue;
    }
    $clean_steps[] = $clean_step;
}