1

I've got the following text :

NOTEU START

#Line1  #

#Line2  #

#Line3  #

#Line4  #

NOTEU END

I explode the text at every pound sign:

$noteText = explode("#", $message);

Producing an array :

  ( [0] => [1] => Line1 [2] => [3] => Line2 [4] => [5] => Line3 [6] => [7] => Line4 [8] => )

I get empty elements in the array which represent the spaces between two consecutive pound signs.

My end goal is to split each line (text inside pound signs) into an array.

This can be achieved by removing these empty array elements however I can't seem to remove them, I've tried :

print_r(array_filter($noteText));

foreach($noteText as $key => $val) {
   if ($val == "") unset($noteText[$key]);
}

Which has no effect on removing these empty spaces.

1
  • I'd go with regular expressions, as Gal suggests; a simple preg_match_all("/#(?P<lines>.*)#/", $input, $result); seems to give the right result (in $result['lines'])) for your input... Commented Jan 31, 2015 at 20:12

2 Answers 2

2

Try using a combination of array_map(), trim(), and array_filter() to remove white spaces and then remove empty elements.

$nodetext= array_filter(array_map("trim", $nodetext));

Using array_map() and trim() together will take the elements that are just white space and turn them into empty strings. array_filter() without a callback will remove empty array values from an array.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes!! That's exactly the answer I was looking for, I knew array_filter and knew there was while space but you put that together with trim. Thanks!
2

Usually lines are seperated by \r\n [windows] \n [linux] or \r [mac] so you could use it. if the lines arent formatted with those line breaks you could easily explode it using regular expressions -

$text ="
#Line1  #

#Line2  #

#Line3  #

#Line4  #
";
preg_match_all("!\#(.*)  #!",$text,$matches);

var_dump($matches[1]);

2 Comments

A single \r hasn't been used on Macs for decades; OS X is BSD-derived and uses \n like other unix variants.
Thanks Matt,not really a mac fan (:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.