Take the 2-minute tour ×

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[#,#].

share|improve this question
add comment

4 Answers

up vote 3 down vote accepted

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).

share|improve this answer
Then why doesn't my first PHP example work? –  Alec Gorge Feb 6 '10 at 18:42
@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 Feb 6 '10 at 18:45
What results do you get? It works for me. –  Tomas Markauskas Feb 6 '10 at 18:46
add comment

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

share|improve this answer
Thanks for the string link, I had been look for something like that. –  Alec Gorge Feb 6 '10 at 18:56
add comment

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('lo')            #=> 3
   "hello".index('a')             #=> nil
   "hello".index(101)             #=> 1
   "hello".index(/[aeiou]/, -3)   #=> 4
share|improve this answer
As I said above, they doesn't my first example work then? –  Alec Gorge Feb 6 '10 at 18:45
@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 Feb 6 '10 at 18:48
add comment

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.

share|improve this answer
add comment

Your Answer


