php проверить есть ли символ в строке

ctype_digit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_digit — Проверяет наличие цифровых символов в строке

Описание

Проверяет, являются ли все символы в строке text цифровыми.

Список параметров

Возвращаемые значения

Примеры

Пример #1 Пример использования ctype_digit()

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

Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел

Смотрите также

User Contributed Notes 14 notes

All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: «123»).
3. ctype_digit() excepts all numbers to be strings (like: «123») and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII ‘0’-‘9’) and false for the rest.

(Note: the PHP type must be an int; if you pass strings it works as expected)

Источник

strripos

strripos — Возвращает позицию последнего вхождения подстроки без учёта регистра

Описание

Список параметров

Строка, в которой производится поиск.

Фактически это будет последнее вхождение needle без учёта offset последних байт.

Возвращаемые значения

Возвращает номер позиции последнего вхождения needle относительно начала строки haystack (независимо от направления поиска и смещения (offset)).

Замечание: Позиция в строке строки отсчитывается от 0, а не от 1.

Список изменений

ВерсияОписание
8.0.0Передача целого числа ( int ) в needle больше не поддерживается.
7.3.0Передача целого числа ( int ) в needle объявлена устаревшей.

Примеры

Пример #1 Пример использования strripos()

= ‘ababcd’ ;
$needle = ‘aB’ ;

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

Смотрите также

User Contributed Notes 7 notes

Simple way to implement this function in PHP 4

OK, I guess this will be the final function implementation for PHP 4.x versions ( my previous posts are invalid )

Suppose you just need a stripos function working backwards expecting that strripos does this job, you better use the following code of a custom function named strbipos:

Sorry, I made that last post a bit prematurely. One more thing wrong with the simple php4 version is that it breaks if the string is not found. It should actually look like this:

strripos() has very strange behaviour when you provide search position. For some reason it searches forward from the given position, instead of searching backward, that is more logical.

Источник

strrpos

(PHP 4, PHP 5, PHP 7, PHP 8)

strrpos — Возвращает позицию последнего вхождения подстроки в строке

Описание

Список параметров

Строка, в которой производится поиск.

Фактически это будет последнее вхождение needle без учёта offset последних байт.

Возвращаемые значения

Возвращает номер позиции последнего вхождения needle относительно начала строки haystack (независимо от направления поиска и смещения (offset)).

Замечание: Позиция в строке строки отсчитывается от 0, а не от 1.

Список изменений

ВерсияОписание
8.0.0Передача целого числа ( int ) в needle больше не поддерживается.
7.3.0Передача целого числа ( int ) в needle объявлена устаревшей.

Примеры

Пример #1 Проверка существования искомой строки

Легко ошибиться и перепутать возвращаемые значения в случаях «символ найден в нулевой позиции» и «символ не найден». Вот так можно узнать разницу:

Пример #2 Поиск со смещением

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

Смотрите также

User Contributed Notes 35 notes

The documentation for ‘offset’ is misleading.

It says, «offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string.»

This is confusing if you think of strrpos as starting at the end of the string and working backwards.

A better way to think of offset is:

— If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won’t find the needle).

— If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won’t be found.

If, for example, you want to find the last space in a string before the 50th character, you’ll need to do something like this:

If instead you used strrpos($text, » «, 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.

Ten years on, Brian’s note is still a good overview of how offsets work, but a shorter and simpler summary is:

Or to put it another way, a positive number lets you search the rightmost section of the string, while a negative number lets you search the leftmost section of the string.

Both these variations are useful, but picking the wrong one can cause some highly confusing results!

Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function):

if ($pos === false)
return false;

Note: supports full strings as needle

The description of offset is wrong. Here’s how it works, with supporting examples.

Offset effects both the starting point and stopping point of the search. The direction is always right to left. (The description wrongly says PHP searches left to right when offset is positive.)

Here’s how it works:
When offset is positive, PHP searches right to left from the end of haystack to offset. This ignores the left side of haystack.

When offset is negative, PHP searches right to left, starting offset bytes from the end, to the start of haystack. This ignores the right side of haystack.

Example 1:
$foo = ‘aaaaaaaaaa’;
var_dump(strrpos($foo, ‘a’, 5));
Result: int(10)

Example 2:
$foo = «aaaaaa67890»;
var_dump(strrpos($foo, ‘a’, 5));
Result: int(5)

Conclusion: When offset is positive, PHP searches right to left from the end of haystack.

Example 3:
$foo = «aaaaa567890»;
var_dump(strrpos($foo, ‘a’, 5));
Result: bool(false)

Conclusion: When offset is positive, PHP stops searching at offset.

Conclusion: When offset is negative, PHP searches right to left, starting offset bytes from the end.

Conclusion: When offset is negative, PHP searches right to left, all the way to the start of haystack.

To understand this instinctively, just imagine the characters being replaced with invalid symbols. Here’s an example:

$offset is very misleading, here is my understanding:

This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.

Maybe I’m the only one who’s bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here’s an example to explain what I don’t like:

The quick brown fox jumps over the lazy
dog.

So that’s why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with ‘ ‘.

I’ve got a simple method of performing a reverse strpos which may be of use. This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.

Here is an example of backwards stepping through instances of a string with this function:

With Test2 the first line checks from the first 3 in «12341234» and runs backwards until it finds a 1 (at position 0)

The second line checks from the second 2 in «12341234» and seeks towards the beginning for the first 1 it finds (at position 4).

This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.

I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.

This did the trick:

The «find-last-occurrence-of-a-string» functions suggested here do not allow for a starting offset, so here’s one, tried and tested, that does:

refering to the comment and function about lastIndexOf().
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle. i rewrote it as fallows:

SILENT WIND OF DOOM WOOSH!

Full strpos() functionality, by yours truly.

Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.

i wanted to find a leading space BEFORE a hyphen

Crude Oil (Dec) 51.00-56.00

so I had to find the position of the hyphen

then subtract that position from the length of the string (to make it a negative number)
and then walk left toward the beginning of the string, looking for the first space before the hyphen

I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters. This is a recursive function. I have not tested to see if it is more or less efficient than the others on the page. I hope this helps someone!

I needed to remove last directory from an path, and came up with this solution:

?>

Might be helpful for someone..

If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don’t have mb_strrpos working, try this:

Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.

I was looking for the equivalent of Java’s lastIndexOf(). I couldn’t find it so I wrote this:

Источник

Функции для работы со строками

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

Содержание

User Contributed Notes 24 notes

In response to hackajar yahoo com,

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

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’
*/

to: james dot d dot baker at gmail dot com

PHP has a builtin function for doing what your function does,

/**
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 ‘/’.

//
// 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 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

Here’s a simpler «simplest» way to toggle through a set of 1..n colors for web backgrounds:

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

Источник

Функции работы со строками в PHP

Особенности операторов сравнения применительно к строкам.

Функция chop( ) возвращает строку после удаления из нее завершающих пропусков и символов новой строки. Синтаксис функции chop( ):

string chop(string строка)

В следующем примере функция chop( ) удаляет лишние символы новой строки:

str_pad()

Функция str_pad( ) выравнивает строку до определенной длины заданными символами и возвращает отформатированную строку. Синтаксис функции str_pad( ):

string str_pad (string строка, int длина_дополнения [, string дополнение [, int тип_дополнения]])

Если необязательный параметр дополнение не указан, строка дополняется пробелами. В противном случае строка дополняется заданными символами. По умолчанию строка дополняется справа; тем не менее, вы можете передать в параметре тип_дополнения константу STR_PAD_RIGHT, STR_PAD_LEFT или STR_PAD_BOTH, что приведет к дополнению строки в заданном направлении. Пример демонстрирует дополнение строки функцией str_pad( ) с параметрами по умолчанию: В следующем примере используются необязательные параметры функции str_pad( ):

Функция trim( ) удаляет псе пропуски с обоих краев строки и возвращает полученную строку. Синтаксис функции trim( ):

string trim (string страна]

К числу удаляемых пропусков относятся и специальные символы \n, \r, \t, \v и \0.

ltrim()

Функция lrim( ) удаляет все пропуски и специальные символы с левого края строки и возвращает полученную строку. Синтаксис функции ltrim( ):

string ltrim (string строка)

Функция удаляет те же специальные символы, что и функция trim( ).

strlen()

int strlen (string строка)

Следующий пример демонстрирует определение длины строки функцией strlen( ):

Сравнение двух строк

strcmp()

Функция strcmp( ) сравнивает две строки с учетом регистра символов. Синтаксис функции strcmp( ): int strcmp (string строка1, string строка2)

В следующем фрагменте сравниваются две одинаковые строки:

strcasecmp()

int strcasecmp (string cтpoкa1, string строка2)

В следующем фрагменте сравниваются две одинаковые строки:

strspn()

Функция strspn( ) возвращает длину первого сегмента строки1, содержащего символы, присутствующие в строке2. Синтаксис функции strspn( ):

int strspn (string строка1, string строка2)

Следующий фрагмент показывает, как функция strspn( ) используется для проверки пароля:

strcspn()

Функция strcspn( ) возвращает длину первого сегмента строки1, содержащего символы, отсутствующие в строке2. Синтаксис функции strcspn( ):

int strcspn (string строка1, string строка2)

В следующем фрагменте функция strcspn( ) используется для проверки пароля:

Обработка строковых данных без применения регулярных выражений

При обработке больших объемов информации функции регулярных выражений сильно замедляют выполнение программы. Эти функции следует применять лишь при обработке относительно сложных строк, в которых регулярные выражения действительно необходимы. Если же анализ текста выполняется по относительно простым правилам, можно воспользоваться стандартными функциями РНР, которые заметно ускоряют обработку. Все эти функции описаны ниже.

strtok()

Функция strtok( ) разбивает строку на лексемы по разделителям, заданным вторым параметром. Синтаксис функции strtok( ):

string strtok (string строка, string разделители)

parse_str()

Функция parse_str( ) выделяет в строке пары и присваивает значения переменных в текущей области видимости. Синтаксис функции parse_str( ):

void parse_str (string строка)

Функция parse_str( ) особенно удобна при обработке URL, содержащих данные форм HTML или другую расширенную информацию. В следующем примере анализируется информация, переданная через URL. Строка представляет собой стандартный способ передачи данных между страницами либо откомпилированных в гиперссылке, либо введенных в форму HTML:

Поскольку эта функция создавалась для работы с URL, она игнорирует символ амперсанд (&).

explode()

Функция explode() делит строку на элементы и возвращает эти элементы в виде массива. Синтаксис функции explode():

array explode (string разделитель, string строка [, int порог])

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

Разделение строки функцией explode( ) продемонстрировано в следующем примере:

Функция explode( ) практически идентична функции регулярных выражений POSIX split( ), описанной выше. Главное различие заключается в том, что передача регулярных выражений в параметрах допускается только при вызове split( ).

implode()

string implode (string разделитель, array фрагменты)

Формирование строки из массива продемонстрировано в следующем примере:

strpos()

Функция strpos( ) находит в строке первый экземпляр заданной подстроки. Синтаксис функции strpos():

int strpos (string строка, string подстрока [, int смещение])

Необязательный параметр offset задает позицию, с которой должен начинаться поиск. Если подстрока не найдена, strpos() возвращает FALSE (0).

В следующем примере определяется позиция первого вхождения даты в файл журнала:

strrpos()

Функция strrpos( ) находит в строке последний экземпляр заданного символа. Синтаксис функции strrpos( ):

int strpos (string строка, char символ)

str_replace()

Функция str_replace( ) ищет в строке все вхождения заданной подстроки и заменяет их новой подстрокой. Синтаксис функции str_replace( ):

string str_replace (string подстрока, string замена, string строка)

Функция substr_replace( ), описанная ниже в этом разделе, позволяет провести заме ну лишь в определенной части строки. Ниже показано, как функция str_replace( ) используется для проведения глобальной замены в строке.

Если подстрока ни разу не встречается в строке, исходная строка не изменяется:

strstr()

Функция strstr( ) возвращает часть строки, начинающуюся с первого вхождения заданной подстроки. Синтаксис функции strstr( ):

string strstr (string строка, string подстрока)

В следующем примере функция strstr( ) используется для выделения имени домена из URL:

substr()

Функция substr( ) возвращает часть строки, начинающуюся с заданной начальной позиции и имеющую заданную длину. Синтаксис функции substr( ):

string substr (string строка, int начало [, int длина])

Помните о том, что параметр начало определяет смещение от первого символа строки; таким образом, возвращаемая строка в действительности начинается с символа с номером (начало + 1).

Следующий пример демонстрирует выделение части строки функцией substr( ):

Пример с положительным параметром длина: Пример с отрицательным параметром длина:

substr_count()

substr_replace()

Функция substr_replace( ) заменяет часть строки, которая начинается с заданной позиции. Если задан необязательный параметр длина, заменяется фрагмент заданной длины; в противном случае производится замена по всей длине заменяющей строки. Синтаксис функции substr_replace( ):

string substr_replace (string строка, string замена, int начало [, int длина])

Простая замена текста функцией substr_replace( ) продемонстрирована в следующем примере:

Alessia’s favorite links

Преобразование строк и файлов к формату HTML и наоборот

Преобразовать строку или целый файл к формату, подходящему для просмотра в web-браузере (или наоборот), проще, чем может показаться на первый взгляд. В РНР для этого существуют специальные функции.

Преобразование текста в HTML

nl2br()

Функция nl2br() заменяет все символы новой строки (\n) эквивалентными конструкциями HTML.

Синтаксис функции nl2br():

string nl2br (string строка)

htmlentities()

Функция htmlentities( ) преобразует символы в эквивалентные конструкции HTML. Синтаксис функции htmlentities:

string htmlentities (string строка)

В следующем примере производится необходимая замена символов строки для вывода в браузере:

htmlspecialchars()

Функция htmlspecialchars( ) заменяет некоторые символы, имеющие особый смысл в контексте HTML, эквивалентными конструкциями HTML. Синтаксис функции htmlspecialchars( ):

string htmlspecialchars (string строка)

Функция html special chars( ) в настоящее время преобразует следующие символы: & преобразуется в &; » » преобразуется в «; преобразуется в >.

Следующий пример демонстрирует удаление потенциально опасных символов функцией htmlspeclalchars( ):

Если функция htmlspecialchars( ) используется в сочетании с nl2br( ), то последнюю следует вызывать после htmlspecialchars( ). В противном случае конструкции
, сгенерированные при вызове nl2br( ), преобразуются в видимые символы.

get_html_translation_table()

Функция get_html_translation_table( ) обеспечивает удобные средства преобразования текста в эквиваленты HTML Синтаксис функции get_htrril_translation_table( ):

string get_html_translation_table (int таблица)

Функция get_html_translation_table( ) возвращает одну из двух таблиц преобразования (определяется параметром таблица), используемых в работе стандартных функций htmlspecialchars( ) и htmlentities( ). Возвращаемое значение может использоваться в сочетании с другой стандартной функцией, strtr(), для преобразования текста в код HTML.

В следующем примере функция get_html_translation_table( ) используется при преобразовании текста в код HTML:

В следующем примере исходный текст восстанавливается функцией array_flip( ):

strtr()

Функция strtr( ) транслирует строку, то есть заменяет в ней все символы, входящие в строку источник, соответствующими символами строки приемник. Синтаксис функции strtr( ):

string strtr (string строка, string источник, string приемник)

Если строки источник и приемник имеют разную длину, длинная строка усекается до размеров короткой строки.

Преобразование HTML в простой текст

Иногда возникает необходимость преобразовать файл в формате HTML в простой текст. Функции, описанные ниже, помогут вам в решении этой задачи.

strip_tags()

Функция strip_tags( ) удаляет из строки все теги HTML и РНР, оставляя в ней только текст. Синтаксис функции strip_tags( ):

string strip_tags (string строка [, string разрешенные_тerи])

Необязательный параметр разрешенные_теги позволяет указать теги, которые должны пропускаться в процессе удаления.

Ниже приведен пример удаления из строки всех тегов HTML функцией strip_tags( ):

В следующем примере удаляются не все, а лишь некоторые теги:

Удаление тегов из текста также производится функцией fgetss().

get_meta_tags()

Хотя функция get_meta_tags( ) и не имеет прямого отношения к преобразованию текста, зто весьма полезная функция, о которой следует упомянуть. Синтаксис функции get_meta_tags( ):

array get_meta_tags (string имя_файла/URL [, int включение_пути])

Функция get_meta_tags( ) предназначена для поиска в файле HTML тегов МЕТА.

Интересная подробность: данные тегов МЕТА можно извлекать не только из файлов, находящихся на сервере, но и из других URL.

Преобразование строки к верхнему и нижнему регистру

strtolower( )

Функция strtolower( ) преобразует все алфавитные символы строки к нижнему регистру. Синтаксис функции strtolower():

string strtolower(string строка)

Неалфавитные символы функцией не изменяются. Преобразование строки к нижнему регистру функцией strtolower() продемонстрировано в следующем примере:

strtoupper()

Строки можно преобразовывать не только к нижнему, но и к верхнему регистру. Преобразование выполняется функцией strtoupper(), имеющей следующий синтаксис:

string strtoupper (string строка)

Неалфавитные символы функцией не изменяются. Преобразование строки к верхнему регистру функцией strtoupper() продемонстрировано в следующем примере:

ucfirst()

string ucfirst (string строка)

Неалфавитные символы функцией не изменяются. Преобразование первого символа строки функцией ucfirst() продемонстрировано в следующем примере:

ucwords()

Функция ucwords( ) преобразует к верхнему регистру первую букву каждого слова в строке. Синтаксис функции ucwords():

string ucwords (string строка»)

Неалфавитные символы функцией не изменяются. «Слово» определяется как последовательность символов, отделенная от других элементов строки пробелами. В следующем примере продемонстрировано преобразование первых символов слов функцией ucwords( ):

strrchr()

Если подстрока не найдена, возвращает FALSE.

В отличие от strchr(), если искомая строка состоит более чем из одного символа, используется только первый символ.

Если второй параметр не является строкой, он приводится к целому и трактуется как код символа.

highlight_string()

mixed highlight_string (string str [, bool return])

Функция highlight_string() выводит версию с расцвеченным синтаксисом строки str, используя цвета, определённые во встроенном выделении синтаксиса PHP.

Если второй параметр return имеет значение TRUE, то highlight_string() возвратит версию раскрашенного кода как строку, вместо её печати. Если второй параметр не имеет значение TRUE, highlight_string() возвратит TRUE при успехе, FALSE при неудаче.

addslashes()

Возвращает сроку, в которой перед каждым спецсимволом добавлен обратный слэш (\), например для последующего использования этой строки в запросе к базе данных.

Экранируются одиночная кавычка (‘), дойная кавычка («), обратный слэш (\) и NUL (байт NULL).

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *