I have the following data which is displaying as this
{123456 123456 123456}
{654321 654321 654321}
{123456 123456 123456}
My PHP Code:
$myarray = preg_split("/(\s|{\s)/", $data);
print_r($myarray);
The output of my array is like this:
[0] => {123456
[1] => 123456
[2] => 123456}
[3] => {654321
[4] => 654321
[5] => 654321}
[6] => {123456
[7] => 123456
[8] => 123456}
My question is, how to hide [0], [3] and [6] from the output? if you noticed, they start with a {
I'm not sure if I did a mistake coding the preg_split
function
Desired behavior:
if the data is like this
{1 2 3}
{4 5 6}
{7 8 9}
the desired output should be like this:
[0] => 2
[1] => 3
[2] => 5
[3] => 6
[4] => 8
[5] => 9
My Answer:
You can achieve the desired output by modifying your regular expression in the preg_split function. Here's an updated version of your code:
php
$data = "{123456 123456 123456}
{654321 654321 654321}
{123456 123456 123456}";
$myarray = preg_split("/\s+|\{|\}/", $data, -1, PREG_SPLIT_NO_EMPTY);
$myarray = array_slice($myarray, 1); // Remove the first element
print_r($myarray);
This code will split the data by one or more whitespace characters (\s+), {, and }. The PREG_SPLIT_NO_EMPTY flag is used to exclude empty elements from the resulting array. The array_slice function is then used to remove the first element from the array, which is the empty string before the first {.
This should give you the desired output with only the values from the 2nd and 3rd columns.
Rate this post
4 of 5 based on 8724 votesComments