I've added a variable with a long sentence within an array and I have the correct syntax to separate the words. Yet when I try show array key 1,2,3,... I get the error Undefined offset
.
Here is my example code:
$quote = '"';
$string = $quote.'asds dasddsfaf fdf
ewfejfierjfnsdafjafj sdf dwiofjwejf iosad dsfosdofjeijfmkslad f
dfsijioewjo fsdlfa'.$quote;
$newstring = implode('", "', preg_split('/[\s]+/', $string));
$arrayz = array($newstring);
echo $arrayz[2];
Echoing just $newstring
gives me: "asds", "dasddsfaf", "fdf", "ewfejfierjfnsdafjafj", "sdf", "dwiofjwejf", "iosad", "dsfosdofjeijfmkslad", "f", "dfsijioewjo", "fsdlfa"
I think you are over complicating things. There is no need to use preg_split
here. Just use explode() . Try this:
$commer = '"';
$string = $commer.'asds dasddsfaf fdf
ewfejfierjfnsdafjafj sdf dwiofjwejf iosad dsfosdofjeijfmkslad f
dfsijioewjo fsdlfa'.$commer;
$newstring = explode(' ', $string);
print_r($newstring);
Output:
Array
(
[0] => "asds
[1] => dasddsfaf
[2] => fdf
[3] => ewfejfierjfnsdafjafj
[4] => sdf
[5] => dwiofjwejf
[6] => iosad
[7] => dsfosdofjeijfmkslad
[8] => f
[9] => dfsijioewjo
[10] => fsdlfa"
)
Edit, based on comment. This should do what you want:
$commer = '"';
$string = 'asds dasddsfaf fdf ewfejfierjfnsdafjafj sdf dwiofjwejf iosad dsfosdofjeijfmkslad f dfsijioewjo fsdlfa';
$arrayz = array();
foreach(explode(' ', $string) as $word) {
$arrayz[] = $commer . $word . $commer;
}
print_r($arrayz);
Output:
Array
(
[0] => "asds"
[1] => "dasddsfaf"
[2] => "fdf"
[3] => "ewfejfierjfnsdafjafj"
[4] => "sdf"
[5] => "dwiofjwejf"
[6] => "iosad"
[7] => "dsfosdofjeijfmkslad"
[8] => "f"
[9] => "dfsijioewjo"
[10] => "fsdlfa"
)
$commer = '"';
$string = $commer.'asds dasddsfaf fdf
ewfejfierjfnsdafjafj sdf dwiofjwejf iosad dsfosdofjeijfmkslad f
dfsijioewjo fsdlfa'.$commer;
$arrayz = preg_split('/[\s]+/', $string);
echo $arrayz[2];
It's also a good idea to use preg_split('/[\\s]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
so you won't end up with empty entries in case there are double, leading, or trailing spaces.
You have assigned only one element in an array therefore the size of array is only 1 ie; you can access only $arrayz[0]. Try to use in a loop until the string ends and store in concurrently. This might solve.
array($var)
creates an array from another array (if $var
is an array) or a single-element array otherwise. Since implode()
returns a string
from the imploded array, array($newstring)
will create a single-element array that is the imploded string!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.