How to get first 5 characters from string

faressoft picture faressoft · Sep 24, 2010 · Viewed 502.2k times · Source

How to get first 5 characters from string using php

$myStr = "HelloWordl";

result should be like this

$result = "Hello";

Answer

Gumbo picture Gumbo · Sep 24, 2010

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