Reputation:
I want to avoid any empty string in an array or any kind of white space. I'm using the following code:
<?php
$str="category 1
category 2
category 3
category 4
";
$var = nl2br($str);
echo $var."<br>";
$arr = explode("\n", $var);
var_dump($arr); echo "<br>";
for($i = 0; $i < count($arr); $i++) {
if(($arr[$i]) != '')
{
echo $arr[$i]."</br>";
}
}
?>
How can I remove the white space or empty string like the 2,3,5 index in the array which don't have needed string.
Upvotes: 1
Views: 111
Reputation:
Finally I've solved it using the following code. Thanks everyone for you help.
<?php
$str="category 1
category 2
category 3
category 4
";
$arr = explode("\n", $str);
var_dump($arr);
$result = array();
for($i=0;$i<count($arr);$i++) {
if(!preg_match("/^\s*$/", $arr[$i])) $result[] = $arr[$i];
}
$arr = $result;
var_dump($arr);
for($i = 0; $i < count($arr); $i++){
echo $arr[$i]."</br>";
}?>
Upvotes: 0
Reputation: 822
Your code was pretty much correct, but as was pointed out, your nl2br
was adding a <br>
to the end of each line and thus making this a harder process than it should have been.
$str="category 1
category 2
category 3
category 4
";
$arr = explode("\n", $str);
var_dump($arr); echo "<br>";
for($i = 0; $i < count($arr); $i++){
if(($arr[$i]) != '')
{
echo $arr[$i]."</br>";
}
}
I used your old code and just removed the nl2br
line as well as initial echo
and from there onward, your code actually accomplishes your goal because the explode("\n", $str)
is all that you need to split on empty lines and your if
statement covers any lines that happen to be only whitespace.
Upvotes: 0
Reputation: 3795
$array = array_filter(array_map('trim',$array));
Removes all empty values and removes everywhere spaces before and after content!
Upvotes: 1