How to get first 5 characters from string

03/26/2020 22:00:02

How to get first 5 characters from string using php

$myStr = "HelloWordl";

result should be like this

$result = "Hello";

Verified Answer (524 Votes)

09/24/2010 18:29:34

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);
524

Answer #2 (45 Votes)

09/24/2010 18:26:18

Use substr():

$result = substr($myStr, 0, 5);
45

Answer #3 (19 Votes)

01/11/2014 15:13:49

An alternative way to get only one character.

$str = 'abcdefghij';

echo $str{5};
19
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.