Jak uzyskać pierwsze 5 znaków z ciągu

Jak uzyskać pierwsze 5 znaków z Ciągu za pomocą php

$myStr = "HelloWordl";

Wynik powinien wyglądać tak

$result = "Hello";
 180
Author: Foreever, 2010-09-24

6 answers

Dla ciągów jednobajtowych (np. rodzina US-ASCII, ISO 8859 itp.) użycie substr oraz dla ciągów wielobajtowych (np. UTF-8, UTF-16, itd.) użycie mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);
 396
Author: Gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-24 13:29:34

Użycie substr():

$result = substr($myStr, 0, 5);
 36
Author: BoltClock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-24 13:26:18

Alternatywny sposób na uzyskanie tylko jednego znaku.

$str = 'abcdefghij';

echo $str{5};
 19
Author: Paul Hodel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-11 06:11:02

Możesz użyć substr funkcja taka:

echo substr($myStr, 0, 5);

Drugi argument do substr to z jakiej pozycji chcesz zacząć, a trzeci argument to liczba znaków, które chcesz zwrócić.

 9
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-24 13:26:15

Funkcja substr zrobiłaby to, co chcesz

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

  // output would be hello
 0
Author: Adeojo Emmanuel IMM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-04 11:16:59

Możesz uzyskać wynik po prostu używając substr():

Składnia substr (string, start, length)

Przykład

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

Wyjście:

 Hello
 -3
Author: Prabhu Nandan Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-19 06:07:29