views:

371

answers:

4

I am trying to convert a small bit of Ruby to PHP, and I have had success so far, except for this one line:

string = string[16,string.length-16]

I have tried these two things in PHP:

$string = substr($string, 16, strlen($string) - 16);
// and
$string = substr($string, 16, strlen($string) - 32);

But the problem is that I have no clue what the string[#,#] syntax does. I have seen string[#..#] before and string[#], but never string[#,#].

+3  A: 

string[x,y] is a substring that starts at index x and is y characters (or bytes in 1.8) long (as opposed to string[x..y] which starts at index x and stops at index y).

sepp2k
Then why doesn't my first PHP example work?
Ramblingwood
@Ramblingwood, I see nothing wrong with the PHP. What do you mean that 'it doesn't work'? A syntax error, it's not returning what you want? Are you checking the same strings?
Yar
What results do you get? It works for me.
Tomas Markauskas
+2  A: 

If you look at the Ruby docs you will learn all kinds of strange things. But that syntax is merely the substring and offset, so if you just start an irb and goof around a bit you get

>> "123456789"[3,2]
=> "45"

so you can see what's happening. Anyway, docs are here

str.index(substring [, offset]) => fixnum or nil
str.index(fixnum [, offset]) => fixnum or nil
str.index(regexp [, offset]) => fixnum or nil
Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

   "hello".index('e')             #=> 1
   "hello".index('lo')            #=> 3
   "hello".index('a')             #=> nil
   "hello".index(101)             #=> 1
   "hello".index(/[aeiou]/, -3)   #=> 4
Yar
As I said above, they doesn't my first example work then?
Ramblingwood
@Ramblingwood "doesn't work" is a really hard thing to interpret. We know it's somewhere between "not doing what I want" and "makes my computer explode" but we have to pin it down a bit more to help you.
Yar
+3  A: 

Seems to me that $string = substr($string, 16, strlen($string) - 16); must work... different output?

Oh and more about string in ruby: http://ruby-doc.org/core/classes/String.html#M000771

Adam Kiss
Thanks for the string link, I had been look for something like that.
Ramblingwood
+1  A: 

Judging from the responses and your comments, I have the feeling your error lies elsewhere. Maybe $string is empty. Test your assumptions by printing out all the "obvious" things. The string, the result of strlen(), etc. Also, errors on a preceeding line (such as an unterminated if() ) can give unexpected results.

gbarry