00 Votes

PHP: Read out first X Characters from beginning of String

Question by Guest | 2015-07-14 at 10:51

I would like to read out some of the first characters from a string using PHP. For example, I would like to retry the first 2 or 10 characters of an arbitrary string from the front.

Is there any function for that in PHP?

ReplyPositiveNegative
0Best Answer0 Votes

Yes, the function is called substr(). The result of substr() is a substring from the string, we have passed to the function.

Here is a small example of how to use it.

$s = 'abcdef';

echo substr($s, 0, 1);  // a
echo substr($s, 0, 2);  // ab
echo substr($s, 0, 5);  // abcde

As a first parameter, we are passing our string to substr(). In our example, this is "abcdef".

The second parameter is always 0 in our case. This parameter is indicating the start position of our desired sub-string. Because we always want to start at the beginning of the origin string, which is the position 0, we always have to use 0 for the second parameter.

The third parameter is the desired length of the substring. In other words, that is the number of characters we want to cut out. If we only wanted to get the first character from the string, accordingly, we are passing 1 which is resulting in "a" in our example. In the next two lines, we are using 2 and 5 as length, so that we get "ab" and "abcde" as a result.
2015-07-14 at 14:16

ReplyPositive Negative
Reply

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.

Participate

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