views:

111

answers:

3

How to get first 5 characters from string using php

$myStr = "HelloWordl";

result should be like this

$result = "Hello";
A: 

You can use the substr function like this:

echo substr($myStr, 0, 5);

The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

Sarfraz
+5  A: 

Use substr():

$result = substr($myStr, 0, 5);
BoltClock
`substr("Häagen-Dazs", 0, 5) == "Häag"` - what am i doing wrong?
stereofrog
@stereofrog: You’re probably using a multi-byte character encoding like UTF-8. In that case use `mb_substr`.
Gumbo
+6  A: 

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);
Gumbo
mb_substr() this what i need, thanks
faressoft