Php вывести первой символ строки

Getting the first character of a string with $str[0]

I want to get the first letter of a string and I’ve noticed that $str[0] works great. I am just not sure whether this is ‘good practice’, as that notation is generally used with arrays. This feature doesn’t seem to be very well documented so I’m turning to you guys to tell me if it’s all right – in all respects – to use this notation? Or should I just stick to the good ol’ substr($str, 0, 1) ? Also, I noted that curly braces ( $str <0>) works as well. What’s up with that?

9 Answers 9

Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the [] operator. Usually there’s no problem at all in using $str[0] (and I’m pretty sure is much faster than the substr() method).

There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you’re using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr() . Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.

Читайте также:  Округление чисел си шарп

Does PHP $str[0] take into account that there can be 2Byte long chars? UTF and such? (even though substr() does not help with it either!)

If you want to be extra super safe, you should go with mb_substr($str, 0, 1, ‘utf-8’) so you don’t truncate a multibyte string.

Although this is shorter and is easier to remember than substr($str, 0, 1) , this confuses who reads the code.

The choice between square-brackets and substr() is largely a matter of preference, but be aware that the result is different when applied to an empty string. If $s = «» then $s[] === «», but substr($s, 0, 1) === false.

If $s = «» then $s[0] will generate a «Notice: Uninitialized string offset: 0» whereas substr($s, 0, 1) will not.

The <> syntax is deprecated as of PHP 5.3.0. Square brackets are recommended.

docs.php.net/language.types.string : Note: Strings may also be accessed using braces, as in $str, for the same purpose. However, this syntax is deprecated as of PHP 5.3.0. Use square brackets instead, such as $str[42].

@VolkerK: at the link you provided I noticed they removed the note on the PHP manual they left only: Note: Strings may also be accessed using braces, as in $str<42>, for the same purpose. So I’m wondering if they decided that using <> is NOT deprecated anymore as of PHP 6

«gives no indication of deprecation» — Indeed, the deprecation message has been removed in revision 304518 — The curly-brackets-string-index-accessor-syntax does not emit any deprecation notice, although the original notice have been on and off for PHP 5.x, it does not in the current version, thrus we should not label it as deprecated. Related to bug #52254 — svn.php.net/repository/phpdoc/en/trunk/language/types/…

As of today (10th May’18), a quote from the liked PHP docs: Note: Strings may also be accessed using braces, as in $str, for the same purpose. Seems like this syntax is going to stay for a while.

Lets say you just want the first char from a part of $_POST, lets call it ‘type’. And that $_POST[‘type’] is currently ‘Control’. If in this case if you use $_POST[‘type’][0] , or substr($_POST[‘type’], 0, 1) you will get C back.

However, if the client side were to modify the data they send you, from type to type[] for example, and then send ‘Control’ and ‘Test’ as the data for this array, $_POST[‘type’][0] will now return Control rather than C whereas substr($_POST[‘type’], 0, 1) will simply just fail.

So yes, there may be a problem with using $str[0] , but that depends on the surrounding circumstance.

As a side note to circumvent this particular issue and in either case one should always perform data validation. if (true === is_string($_POST[‘type’]))

My only doubt would be how applicable this technique would be on multi-byte strings, but if that’s not a consideration, then I suspect you’re covered. (If in doubt, mb_substr() seems an obviously safe choice.)

However, from a big picture perspective, I have to wonder how often you need to access the ‘n’th character in a string for this to be a key consideration.

In case of multibyte (unicode) strings using str[0] can cause a trouble. mb_substr() is a better solution. For example:

$first_char = mb_substr($title, 0, 1); 

It’ll vary depending on resources, but you could run the script bellow and see for yourself 😉

; $end3 = microtime(true); $time3[$i] = $end3 - $start3; > $avg1 = array_sum($time1) / $tests; echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL; $avg2 = array_sum($time2) / $tests; echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL; $avg3 = array_sum($time3) / $tests; echo 'the average float microtime using "array<>" is '. $avg3 . PHP_EOL; ?> 

Some reference numbers (on an old CoreDuo machine)

$ php 1.php the average float microtime using "array[]" is 1.914701461792E-6 the average float microtime using "substr()" is 2.2536706924438E-6 the average float microtime using "array<>" is 1.821768283844E-6 $ php 1.php the average float microtime using "array[]" is 1.7251944541931E-6 the average float microtime using "substr()" is 2.0931363105774E-6 the average float microtime using "array<>" is 1.7225742340088E-6 $ php 1.php the average float microtime using "array[]" is 1.7293763160706E-6 the average float microtime using "substr()" is 2.1037721633911E-6 the average float microtime using "array<>" is 1.7249774932861E-6 

It seems that using the [] or <> operators is more or less the same.

Источник

PHP: substr и мощные альтернативы, чтобы вырезать часть строки

Поговорим о том, как обрезать строку в PHP. Функция substr в предназначена для получения части строки. Она выделяет подстроку из переданной строки и возвращает её. Для этого нужно указать строку, порядковый номер символа, начиная с которого нужно вырезать строку, порядковый номер символа, до которого мы верезаем подстроку.

Обратите внимание, что substr неправильно работает с многобайтовыми кодировками, поэтому мы будем использовать mb_substr, которая работает с ними корректно. Об этой проблеме немного ниже.

mb_substr( string $string, int $start, int|null $length = null, string|null $encoding = null ): string
  • $string — строка, из которой мы будем вырезать подстроку
  • $start — символ, с которого мы будем вырезать подстроку
  • $length — сколько символов мы будем вырезать (по умолчанию будем вырезать все оставшиеся)
  • $encoding — кодировка

Теперь перейдем к примерам.

Получаем строку начиная с определенного символа

$url = 'https://phpstack.ru/admin/'; $result = mb_substr($url, 8); echo $result; // результат: phpstack.ru/admin/

Мы вырезали первые 8 символов из строки, содержащей URL адрес.

Получаем определенное количество символов

Теперь давайте вырежем еще и «/admin/» в конце.

Мы бы могли сделать это указав количество символов, которое нужно взять, оно равно количеству символов в домене, их 11

$url = 'https://phpstack.ru/admin/'; $result = mb_substr($url, 8, 11); // возьмем 11 символов начиная с 8-го echo $result; // результат: phpstack.ru

Вырезаем символы с конца

Что если мы не знаем количества символов в домене, но знаем что нужно вырезать строку «/admin/», длина которой составляет 7 символов? Иными словами нам нужно вырезать с конца.

В таком случае нужно указать отрицательное число:

$url = 'https://phpstack.ru/admin/'; $result = mb_substr($url, 8, -7); // удаляем 8 символов с начала и 7 символов с конца echo $result; // результат: phpstack.ru

Получаем несколько последних символов

Что если нам нужно вернуть наоборот только 7 последних символов? Тогда код будет следующим:

$url = 'https://phpstack.ru/admin/'; $result = mb_substr($url, -7); // Получаем 7 символов с конца, остальное удаляем echo $result; // результат: /admin/

Получаем первый символ строки

$url = 'https://phpstack.ru/admin/'; $result = mb_substr($url, 0, 1); // Начиная с 0 берем 1 символ echo $result; // результат: h

Получаем последний символ строки

$url = 'https://phpstack.ru/admin/'; $result = mb_substr($url, -1); // начинаем на 1 символ относительно конца echo $result; // результат: /

Получение подстроки по регулярному выражению

Если вам не хватает возможностей substr, возможно вам необходим более мощный инструмент: preg_match — эта функция позволяет получить подстроки по регулярному выражению.

Проблема при работе с многобайтовыми кодировками.

$url = 'привет'; $result1 = mb_substr($url, 3); // удаляем 3 символа с начала $result2 = substr($url, 3); // удаляем 3 символа с начала var_dump($result1); // вет var_dump($result2); // �ивет

Что случилось? Почему в первом случае, где мы использовали mb_substr все сработало хорошо, а во втором случае вернулся какой-то битый символ?

Дело в том, что в UTF-8 кириллица кодируется 2 байтам, вместо одного. substr считает, что символ равен байту и поэтому вырезает 3 байта с начала. Таким образом она вырезала букву «П», и только половину буквы «Р». В общем вы поняли: всегда используйте mb_substr когда работаете с текстом, который потенциально может содержать многобайтовые символы.

Продвинутая работа со строками

Если вы часто работаете со строками, вам пригодится это расширение: symfony/string

С его помощью вы сможете легко вырезать строки. Взгляните на несколько примеров:

// returns a substring which starts at the first argument and has the length of the // second optional argument (negative values have the same meaning as in PHP functions) u('Symfony is great')->slice(0, 7); // 'Symfony' u('Symfony is great')->slice(0, -6); // 'Symfony is' u('Symfony is great')->slice(11); // 'great' u('Symfony is great')->slice(-5); // 'great' // reduces the string to the length given as argument (if it's longer) u('Lorem Ipsum')->truncate(3); // 'Lor' u('Lorem Ipsum')->truncate(80); // 'Lorem Ipsum' // the second argument is the character(s) added when a string is cut // (the total length includes the length of this character(s)) u('Lorem Ipsum')->truncate(8, '…'); // 'Lorem I…' // if the third argument is false, the last word before the cut is kept // even if that generates a string longer than the desired length u('Lorem Ipsum')->truncate(8, '…', false); // 'Lorem Ipsum'

Источник

Php вывести первой символ строки

Для иллюстрации получения символа строки нам потребуется какая-то строка:

Опять предположим, что нам потребуется 5 символ нашей строки, поступаем как с массивом и выедем определенный символ строки с помощью echo:

Результат получения и вывода определенного символа строки:

Если вы были внимательны, то должны были обратить внимание, на то, что буква выводится 6 по счету. а нам нужна была 5. дело в том, что здесь работает тоже правило, что и с массивом. счет начинается с нуля. и [0] это 1. как бы странно это не звучало! смайлы , возможно, что через несколько лет вы привыкните, а может и нет. смайлы

Получить символ строки кириллица utf-8

В свое время я пересел на кодировку utf-8, почему!? Да просто как-то притомился с вылезанием постоянных крокозябер!
Мы победили крокозябры, но! Проблема в том. что php(редиска, это не такая уж большая проблема. если вы знаете, что делать) не очень любит кириллицу в кодировке utf-8, у нас будет отдельная страница в utf-8 не работает, поэтому не будем растекаться по древу.

Как получить символ строки кириллица utf-8

Для иллюстрации получения символа строки в кириллице, нам потребуется эта самая строка на кириллице.

Если мы проделаем тоже, что было применено в выше идущем пункте.

Как я не пытался различными способами решить именно такой способ получения символа строки, увы я не смог решить этот ребус! Но. разве это когда-то нас останавливало!? У нас есть для этого функция, которые в состоянии получить определенный символ строки. получим. пусть это будет первый элемент строки:

Нам нужно перекодировать строку в windows-1251 применяем функцию substr, третьим значением ставим тот символ строки который хотим получить, и третьим шагом возвращаем кодировку строки.

$string_1 = ‘Привет мир!’;
$stroka = iconv(‘UTF-8′,’windows-1251’,$string_1 ); //Меняем кодировку на windows-1251
$stroka = substr($stroka , 0 , 1); //Получаем требуемый(1) символ строки
$stroka = iconv(‘windows-1251′,’UTF-8’,$stroka ); //Меняем кодировку на windows-1251

Результат получения определенного символа строки:

Получить символ строки кириллица utf-8 -> mb_substr

Вообще, если у вас кириллица, то должна работать функция mb_substr, не то, чтобы, я с утра до вечера пользуюсь функциями с mb, но сколько бы я не использовал их, то всегда с ними что-то не то.

если мы сейчас применим функцию mb_substr:

Для того, чтобы данная функция получила определенный символ строки, то нужно объявить кодировку внутри скрипта.

Результат получения символа строки с помощью mb_substr

Источник

Оцените статью