0

Below script is shown search string in a text file, my text file has contents like:

60, 1, 1, 188, pdgje5566

60, 1, 1, 188, pdgje5565

if(!empty($extTxId)){
$searchfor = $extTxId;

$matches = array();

$handle = @fopen($file, "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchfor) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

print_r($matches);

it output as

Array ( [0] => 60, 1, 1, 188, ppje5566 )

However, I want to explode the data which is separate by comma(,) and store into variable, is that anyway to do it?

1
  • 3
    Ummm, you mean $tokens = explode(",", $str); ? The function is literally called explode. Commented Sep 25, 2012 at 13:37

4 Answers 4

4

i want to explode the data which is separate by comma(,)

Use explode().

If this is a CSV file (or some other delimited file), I suggest looking at fgetcsv(). It is effectively fgets() and explode(), which seems to be what you need.

2
  • i had try explode(",",$matches) but no luck, any sample? Commented Sep 25, 2012 at 13:39
  • 1
    Based on your array, you can't do it on $matches as that is the entire array. You need to do it on the elements, e.g. $matches[0] Commented Sep 25, 2012 at 13:40
2

Since you have spaces between each comma, you can trim each element.

// Iterate through each item int the array (you can do $matches[0] if you just want the first)
foreach ($matches as $match)
{
     $output_array = array_map('trim',explode(',',$match));

     print_r($output_array);
}

Output:

Array
(
    [0] => 60
    [1] => 1
    [2] => 1
    [3] => 188
    [4] => pdgje5565
)

Example: http://codepad.org/aSyVX5Bj

4
  • 1
    Not really, if one doesn't happen to have a space, you're screwed. Commented Sep 25, 2012 at 13:43
  • Agreed. fgetcsv() will account for this though. Most of these answers simply rebuild its functionality. Commented Sep 25, 2012 at 13:46
  • I realize, but he wasn't using fgetcsv(), which is why I answered in this manner Commented Sep 25, 2012 at 13:47
  • heh, agreed, much better in this instance. Commented Sep 25, 2012 at 13:48
0

Try like

foreach(Array[0] as $element)
{
     echo $element;
}
0

If you know the exact structure of the input you're getting, you could do something like:

$string = '60, 1, 1, 188, pdgje5565';
// Using trim just to be sure
list($varA, $varB, $varC, $varD, $varE) = explode(', ', trim($string));

This way you would get the results as follows:

$varA = 60;
$varB = 1;
$varC = 1;
$varD = 188;
$varE = 'pdgje5565';

The main advantage here is you would get decent variables instead of array with abstract indexes, but it is only good if you're sure about you're structure being constant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.