0

I don't understant why my explode doesn't work :

I have an array :

array(6) { 
[0]=> string(0) "" 
[1]=> string(21) " Subject Hello World " 
[2]=> string(57) " Bonjour se jserais base sdf sdf sd f sqdf qsfd " 
[3]=> string(22) " [email protected] " 
[4]=> string(12) " hello byee " 
[5]=> string(11) " loul fund " } 

I want to creat an another tab for element 4 an 5. I try an

$one = explode(" ", $this->connect[4]);
var_dump($one); 

But the result is :

array(1) { [0]=> string(12) " hello byee " } 

and not :

array(1) { [0]=> string(4) "hello" [1]=>string(4) "byee" } 

Do you no why ?

10
  • 1
    Technically your array should consist of 4 elements because you have two spaces surrounding each string. Use trim() to remove those. Commented Apr 26, 2013 at 8:42
  • 1
    What's the result of var_dump($this->connect[4]); ? Commented Apr 26, 2013 at 8:42
  • 4
    Are those spaces in the string or some other form of white space? Commented Apr 26, 2013 at 8:44
  • 3
    just for fun, if you want to be sure it is indeed not a space, just do "var_dump(ord($this->connect[4][0]));" I am guessing it will not say it is "32" Commented Apr 26, 2013 at 8:49
  • 1
    Unexpected. that is actually a linefeed. Not any type of whitespace. Commented Apr 26, 2013 at 9:03

2 Answers 2

3

please try this

  $parts = preg_split('/\s+/',$this->connect[4]);
  print_r($parts);
Sign up to request clarification or add additional context in comments.

8 Comments

$parts = preg_split('/\s+/',trim($this->connect[4])); work ! :) Don't understand why explode not... an idea ?
@MartialE the one which you have used is also working for me thats why i have given you alternate solution.
@MartialE \s matches any whitespace character. It must have been some sort of other whitespace character.
@AbsoluteƵERØ there is a function to see the special character?
Thus, MartialE, in this case, explode("\n", $this->connect[4]) would have worked =)
|
1

Working example at http://codepad.org/0uMXe9Js.

<?php
$connect = array(
    '',
    ' Subject Hello World ',
    ' Bonjour se jserais base sdf sdf sd f sqdf qsfd ',
    ' [email protected] ',
    ' hello byee ',
    ' loul fund '
);

print_r(explode(' ', $connect[4]));
print_r(explode(' ' , trim($connect[4])));

Output:

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

The problem must be in your array values, are you sure those are really spaces? Use PHP ord function to check them out.

1 Comment

well like @Praveen kalal say, i use an alternative '/\s+/'

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.