проверить последний символ строки php
Как получить последний символ строки в PHP?
Мне нужно получить последний символ строки. Скажем, у меня есть «тестеры» в качестве входной строки, и я хочу, чтобы результат был «s». как я могу сделать это в PHP?
12 ответов
Или для многобайтовых строк:
Я позволю вам угадать результат.
Кроме того, я добавил это в код производительности xenonite со следующими результатами:
substr () заняла 7,0334868431091секунду
доступ к массиву занял 2.3111131191254секунды
Прямой доступ к строке (отрицательное смещение строки) занял 1,7971360683441 секунды
Начиная с PHP 7.1.0, также поддерживаются отрицательные строковые смещения. Итак, если вы идете в ногу со временем, вы можете получить доступ к последнему символу в строке следующим образом:
По просьбе @mickmackusa свой ответ дополняю возможными способами применения:
Я не могу оставлять комментарии, но в отношении ответа FastTrack также помните, что окончание строки может быть только одним символом. Я бы предложил
РЕДАКТИРОВАТЬ: Мой код ниже был кем-то отредактирован, поэтому он не выполняет то, что я указал. Я восстановил исходный код и изменил формулировку, чтобы сделать его более понятным.
trim (или rtrim ) удалит все пробелы, поэтому, если вам действительно нужно проверить наличие пробелов, табуляции или других пробелов, сначала вручную замените различные окончания строк:
Я бы посоветовал обратиться к решению Гордона, поскольку оно более производительно, чем substr ():
Выводит что-то вроде
Я не думаю, что человеку, задавшему вопрос, это было нужно, но у меня возникли проблемы с получением этого последнего символа из строки из текстового файла, поэтому я уверен, что другие столкнутся с аналогичными проблемами.
Вы можете найти последний символ с помощью php разными способами, например substr () и mb_substr ().
Здесь я могу показать вам оба примера:
Строка на разных языках, включая C-Sharp и PHP, также считается массивом символов.
Зная, что теоретически операции с массивами должны быть быстрее, чем операции со строками, которые вы могли бы сделать,
Однако стандартные функции массива, такие как
Не будет работать со строкой.
Siemano, получить только php файлы из выбранного каталога:
Как получить последний символ строки в PHP?
Мне нужно получить последний символ строки. Скажем, у меня есть «тестеры» в качестве входной строки, и я хочу, чтобы результат был «s». как я могу сделать это в PHP?
Или для многобайтовых строк:
Обратите внимание, что это не работает для многобайтовых строк. Если вам нужно работать с многобайтовой строкой, рассмотрите возможность использования mb_* семейства функций string.
Я позволю вам угадать вывод.
Кроме того, я добавил это к коду производительности ксенонита со следующими результатами:
substr () занял 7.0334868431091секунд
доступ к массиву занял 2,3111131191254 секунд
Прямой доступ к строке (отрицательные смещения строки) занял 1.7971360683441секунд
Я не могу оставлять комментарии, но в отношении ответа FastTrack, также помните, что конец строки может быть только один символ. Я бы предложил
РЕДАКТИРОВАТЬ: Мой код ниже был отредактирован кем-то, чтобы он не делал то, что я указал. Я восстановил свой исходный код и изменил формулировку, чтобы сделать его более понятным.
trim (или rtrim ) удалит все пробелы, поэтому, если вам нужно проверить пробел, табуляцию или другие пробелы, сначала вручную замените различные окончания строк:
Начиная с PHP 7.1.0, отрицательные смещения строк также поддерживаются. Итак, если вы идете в ногу со временем, вы можете получить доступ к последнему символу в строке, например так:
По просьбе @mickmackusa я дополняю свой ответ возможными способами применения:
Я бы посоветовал перейти к решению Гордона, так как оно более производительно, чем substr ():
Функции для работы со строками
Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.
Содержание
User Contributed Notes 24 notes
I’m converting 30 year old code and needed a string TAB function:
//tab function similar to TAB used in old BASIC languages
//though some of them did not truncate if the string were
//longer than the requested position
function tab($instring=»»,$topos=0) <
if(strlen($instring)
In response to hackajar yahoo
No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11’s «Strings» article under the «String access and modification by character» heading.
I use these little doo-dads quite a bit. I just thought I’d share them and maybe save someone a little time. No biggy. 🙂
Just a note in regards to bloopletech a few posts down:
The word «and» should not be used when converting numbers to text. «And» (at least in US English) should only be used to indicate the decimal place.
Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
/*
* example
* accept only alphanum caracteres from the GET/POST parameters ‘a’
*/
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.
Any string can (usually) be thought of as being in one of these ‘modes’:
pure = what the user actually typed / what you want to see on the page /
what is actually stored in the DB
gpc = incoming GET, POST or COOKIE data
sql = escaped for passing safely to RDBMS via SQL (also, data from DB
queries and file reads if you have magic_quotes_runtime on—which
is rare)
html = safe for html display (htmlentities applied)
Always knowing what mode your string is in—using these methods to
convert between modes—will prevent SQL injection and cross-site scripting.
This class refers to its own namespace (so it can work in PHP 4—there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.
Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST[‘username’]);
*/
Example: Give me everything up to the fourth occurance of ‘/’.
to: james dot d dot baker at gmail dot com
PHP has a builtin function for doing what your function does,
//
// string strtrmvistl( string str, [int maxlen = 64],
// [bool right_justify = false],
// [string delimter = «
\n»])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to ‘spread’ a string over two lines.
//
I really searched for a function that would do this as I’ve seen it in other languages but I couldn’t find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.
?>
Example: Give me everything up to the fourth occurance of ‘/’.
The functions below:
Are correct, but flawed. You’d need to use the === operator instead:
Here’s a simpler «simplest» way to toggle through a set of 1..n colors for web backgrounds:
Here’s an easier way to find nth.
I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn’t work for me. I found the algorithm at http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function
A comprehensive concatenation function, that works with array and strings
function str_cat () <
$args = func_get_args () ;
Here is a truly random string generator it uses the most common string functions it will work on anywhere.
/*
Written By James Baker, May 27th 2005
sentenceCase($string);
$string: The string to convert to sentence case.
Converts a string into proper sentence case (First letter of each sentance capital, all the others smaller)
Example Usage:
echo sentenceCase(«HELLO WORLD. THIS IS A CAPITALISED SENTENCE. this isn’t.»);
Returns:
Hello world. This is a capitalised sentence. This isn’t.
*/
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.
(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)
/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/
?>
Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using
, and then you can use this function to only return text up to the N’th
.
You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().
= ‘Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.’ ;
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida
I’ve prepared this simple function to obtain a string delimited between tags (not only XML tags!). Anybody needs something like this?.
Get the intersection of two strings using array_intersect
?>
For more advanced comparison you can use array_uintersect as well.
как получить последний символ строки в PHP?
Мне нужно получить последний символ строки. Скажем, у меня есть» тестеры «в качестве входной строки, и я хочу, чтобы результат был»s». как я могу это сделать в PHP?
11 ответов
обратите внимание, что это не работает для многобайтовых строк. Если вам нужно работать с многобайтовую строку, используйте тег mb_* семейство строковых функций.
в up и coming PHP 7.1 вы сможете это сделать (принято rfc для отрицательных смещений строк):
Я позволю вам угадать выход.
кроме того, я добавил Это xenonite это код производительности с этими результатами:
substr () заняло 7.0334868431091 секунд
доступ к массиву занял 2,3111131191254 секунды
прямой доступ к строке 1.7971360683441 секунды
Я не могу оставлять комментарии, но в отношении ответа FastTrack также помните, что окончание строки может быть только одним символом. Я бы предложил
EDIT: мой код ниже был отредактирован кем-то, заставляя его не делать то, что я указал. Я восстановил свой исходный код и изменил формулировку, чтобы сделать ее более ясной.
trim (или rtrim ) будут удалены все пробелы, поэтому, если вам нужно проверить пробел, tab или другие пробелы вручную заменяют сначала различные окончания строк:
Я бы посоветовал пойти на решение Гордона, поскольку оно более эффективно, чем substr ():
выводит что-то вроде
Я не думаю, что человек, который задал вопрос, нуждался в этом, но для меня у меня возникли проблемы с получением последнего символа из строки из текстового файла, поэтому я уверен, что другие столкнутся с аналогичными проблемами.
вы можете найти последний символ, используя php многими способами, такими как substr () и mb_substr ().
Если вы используете многобайтовые кодировки, такие как UTF-8, используйте mb_substr вместо substr
здесь я могу показать вам, как пример:
строка на разных языках, включая C sharp и PHP, также считается массивом символов.
зная, что в теории операции массива должны быть быстрее, чем строковые, которые вы могли бы сделать,
однако, стандартные функции такие, как
не будет работать на строке.
начиная с PHP 7.1.0, отрицательные смещения строк также поддерживаются. Итак, если вы идете в ногу со временем, вы можете получить доступ к последнему символу в строке следующим образом:
Siemano, получить только php файлы из выбранного каталога:
stristr
(PHP 4, PHP 5, PHP 7, PHP 8)
stristr — Регистронезависимый вариант функции strstr()
Описание
Возвращает всю строку haystack начиная с первого вхождения needle включительно.
Список параметров
Строка, в которой производится поиск
needle и haystack обрабатываются без учёта регистра.
Возвращаемые значения
Список изменений
Версия | Описание |
---|---|
8.0.0 | Передача целого числа ( int ) в needle больше не поддерживается. |
7.3.0 | Передача целого числа ( int ) в needle объявлена устаревшей. |
Примеры
Пример #1 Пример использования stristr()
Пример #2 Проверка на вхождение строки
Пример #3 Использование не строки в поиске
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
User Contributed Notes 8 notes
There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.
Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.
Got round this by casting the value to a string.
An example for the stristr() function:
I think there is a bug in php 5.3 in stristr with uppercase Ä containing other character
if you search only with täry it works, but as soon as the word is tärylä it does not. TÄRYL works fine
handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.
//now lets parse the array and return the parameter name and its setting
// since the input is being sent by the user via the command line
//we will use stristr since we don’t care about case sensitivity and
//will convert them as needed later.
//lets grap the parameter name first using a double reverse string
// to get the begining of the string in the array then reverse it again
// to set it back. we will also «trim» off the «=» sign
//now lets get what the parameter is set to.
// again «trimming» off the = sign
// now do something with our results.
// let’s just echo them out so we can see that everything is working
?>
when run from the CLI this script returns the following.
Array index is 0 and value is a.php
Parameter is and is set to
Array index is 1 and value is val1=one
Parameter is val1 and is set to one
Array index is 2 and value is val2=two
Parameter is val2 and is set to two
Array index is 3 and value is val3=three
Parameter is val3 and is set to three