php string help

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

  I am mostly a C programmer, and some parts of PHP have me confused a
little.  I want to build a table of strings from some data -- can someone
tell me if this will work?

I've got a binary data file that originated from C.  The file at one point
contains a list of strings.  So there are a bunch of nonzero characters for
the first string, which ends in a 0, then the next string begins, etc etc
until the sequence of strings is ended by another 0.  (so two zeros in a
row -- the end of the last string, plus a final 0)

I know how long the whole table is, so I read the whole list of strings at
once like this:
   $Table = fread($filepos, $tablesize);

So, is that thing $Table an array?  A string?  both?

Then I want to separate all the strings out into a simple array of
individual strings.  Do I need to step through character and character and
build each string in my final array, like this?

    $stringnum = 0;
    $i = 0;

   while ($Table[$i]) {

        $Strings[$stringnum] =  $Table[$i];
        while ($Table[$i]) {   // march through the string until you hit the
            $Strings[$stringnum] .= $Table[$i];

      $i++; // jump over the 0
      $stringnum++;  // start next string

I just am not sure how PHP deals with these 'substrings' within $Table,
which is technically supposed to be a string itself, right?  Will the above
code work or is that the wrong way to do it? It seems like using the .= to
try to append characters is probably not going to work, but I'm not sure
what other way to try.

I appreciate any suggestions!

Re: php string help

bint contained the following:

Quoted text here. Click to load it

Have you looked at string functions in the manual?  Wouldn't explode()
do what you want?
Geoff Berrow  0110001001101100010000000110
100110001101101111001011100111010101101011 -

Re: php string help

thanks, I just saw explode.  I'm not sure how I could get it to work with
binary 0 as the divider, but I am going to redo my table so that it uses a
regular character instead of 0 -- so that should work.


Quoted text here. Click to load it

Re: php string help

Quoted text here. Click to load it

Null bytes are not treated as string seperators in PHP.


See the manual for ord() and chr() for more info.


Re: php string help

bint escribió:
Quoted text here. Click to load it

PHP is not hard-typed as C but functions do have documented return values:
string fread  ( resource $handle  , int $length  )

Thus $Table is a string.

Quoted text here. Click to load it

Nope. You have a good bunch of array and string functions:

To split around zeros you can just explode().

Although you can get a string offset using [], technically strings are
not character arrays in PHP as in C; they are a type of their own.

-- - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:
-- Mi web de humor satinado:

Site Timeline