00 Votes

PHP: Cut first X Characters from the beginning of String

Question by Compi | 2015-07-13 at 23:48

I have an arbitrary string and I need a PHP function with which I can remove some characters from the beginning of this string.

Independent from the kind of characters, for example, I would like to always cut off the first 5 or 10 characters from the front of the string. Also the length of the string may vary and can be different in each case.

I have already tried a little bit using the function substr(), but I could not find any satisfactory results, because you have to specify the length as the second parameter and I do not know this length before because it depends on the length of the string. Can someone help me?

2Best Answer2 Votes

If you ommit the last character (length) when using the function substr(), automatically the substring beginning at the starting position until the end of the string will be returned.

For example, you can use substr() like that:

$s = 'abcdefg';

echo substr($s, 1);  // bcdefg
echo substr($s, 2);  // cdefg
echo substr($s, 5);  // fg

Accordingly, in the first example, the first character from "abcdefg" is removed so that we get "bcdefg". In the second example, we are moving to first 2 characters and in the last example, the first 5 characters of the string.
2015-07-14 at 00:42

ReplyPositive Negative

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.