How to get first 5 characters from string

2019-01-04 06:44发布

How to get first 5 characters from string using php

$myStr = "HelloWordl";

result should be like this

$result = "Hello";

标签: php substring
6条回答
Anthone
2楼-- · 2019-01-04 07:16

An alternative way to get only one character.

$str = 'abcdefghij';

echo $str{5};
查看更多
闹够了就滚
3楼-- · 2019-01-04 07:21

You can get your result by simply use substr():

Syntax substr(string,start,length)

Example

<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>

Output :

 Hello
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-04 07:26

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);
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-04 07:26

Use substr():

$result = substr($myStr, 0, 5);
查看更多
够拽才男人
6楼-- · 2019-01-04 07:35

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.

查看更多
乱世女痞
7楼-- · 2019-01-04 07:37

the substr function would do just what you want

   $mystr = "hello world"
   $str = substr($mystr, 0, 5);
   echo $str;

  // output would be hello
查看更多
登录 后发表回答