|
 |
CXLVI. Функции обработки строк
Эти функции предназначены для выполнения различных манипуляций со
строками. Более специализированные функции см. в разделах, посвященных
регулярным выражениям и обработке URL.
Для получения общей информации о работе со строками, особенно об
использовании одиночных и двойных кавычек и экранировании символов,
смотрите главу "Строки"
в разделе "Типы" .
Эти функции всегда доступны. Для использования этих функций не требуется проведение установки,
поскольку они являются частью ядра PHP.
Перечисленные ниже константы определены данным расширением и могут быть
доступны только в том случае, если PHP был собран с
поддержкой этого расширения или же в том случае, если
данное расширение подгружается во время выполнения.
- Содержание
- addcslashes -- Экранирует спецсимволы в стиле языка C
- addslashes -- Экранирует спецсимволы в строке
- bin2hex --
Преобразует бинарные данные в шестнадцатиричное представление
- chop -- Псевдоним функции rtrim()
- chr -- Возвращает символ по его коду
- chunk_split -- Разбивает строку на фрагменты
- convert_cyr_string --
Преобразует строку из одной кириллической кодировки в другую
- convert_uudecode --
Преобразует строку из формата uuencode в обычный вид
- convert_uuencode --
Преобразует строку в формат uuencode
- count_chars --
Возвращает информацию о символах, входящих в строку
- crc32 -- Вычисляет CRC32 для строки
- crypt -- Необратимое шифрование (хэширование)
- echo -- Выводит одну или более строк
- explode -- Разбивает строку на подстроки
- fprintf -- Записывает отформатированную строку в поток
- get_html_translation_table --
Возвращает таблицу преобразований, используемую функциями
htmlspecialchars() и
htmlentities()
- hebrev --
Преобразует текст на иврите из логической кодировки в визуальную.
- hebrevc --
Преобразует текст на иврите из логической кодировки в визуальную с
преобразованием перевода строки.
- html_entity_decode --
Преобразует HTML сущности в соответствующие символы
- htmlentities --
Преобразует символы в соответствующие HTML сущности.
- htmlspecialchars_decode --
Преобразует специальные HTML-сущности обратно в соответствующие символы
- htmlspecialchars --
Преобразует специальные символы в HTML сущности
- implode -- Объединяет элементы массива в строку
- join -- Псевдоним функции implode()
- levenshtein --
Вычисляет расстояние Левенштейна между двумя строками
- localeconv -- Возвращает информацию о числовых форматах
- ltrim --
Удаляет пробелы из начала строки
- md5_file -- Возвращает MD5 хэш файла
- md5 -- Возвращает MD5 хэш строки
- metaphone -- Возвращает ключ metaphone для строки
- money_format -- Форматирует число как денежную величину
- nl_langinfo --
Возвращает информацию о языке и локали
- nl2br --
Вставляет HTML код разрыва строки перед каждым переводом строки
- number_format -- Форматирует число с разделением групп
- ord -- Возвращает ASCII код символа
- parse_str -- Разбирает строку в переменные
- print -- Выводит строку
- printf -- Выводит отформатированную строку
- quoted_printable_decode --
Раскодирует строку, закодированную методом quoted printable
- quotemeta -- Экранирует специальные символы
- rtrim --
Удаляет пробелы из конца строки
- setlocale -- Устанавливает локаль
- sha1_file -- Возвращает SHA1 хэш файла
- sha1 -- Возвращает SHA1 хэш строки
- similar_text --
Вычисляет степень похожести двух строк
- soundex -- Возвращает ключ soundex для строки
- sprintf -- Возвращает отформатированную строку
- sscanf --
Разбирает строку в соответствии с заданным форматом
- str_ireplace --
Регистро-независимый вариант функции
str_replace().
- str_pad --
Дополняет строку другой строкой до заданной длины
- str_repeat -- Возвращает повторяющуюся строку
- str_replace --
Заменяет строку поиска на строку замены
- str_rot13 -- Выполняет над строкой преобразование ROT13
- str_shuffle -- Переставляет символы в строке
- str_split --
Преобразует строку в массив
- str_word_count --
Возвращает информацию о словах, входящих в строку
- strcasecmp --
Сравнение строк без учета регистра, безопасное для данных в двоичной
форме
- strchr -- Псевдоним функции strstr()
- strcmp --
Сравнение строк, безопасное для данных в двоичной форме
- strcoll -- Сравнение строк с учетом текущей локали
- strcspn --
Возвращает длину участка в начале строки, не соответствующего маске
- strip_tags -- Удаляет HTML и PHP тэги из строки
- stripcslashes --
Удаляет экранирование символов, произведенное функцией
addcslashes()
- stripos --
Возвращает позицию первого вхождения подстроки без учета регистра
- stripslashes --
Удаляет экранирование символов, произведенное функцией
addslashes()
- stristr --
Регистро-независимый вариант функции strstr().
- strlen -- Возвращает длину строки
- strnatcasecmp --
Сравнение строк без учета регистра с использованием алгоритма
"естественного упорядочения"
- strnatcmp --
Сравнение строк с использованием алгоритма "естественного
упорядочения"
- strncasecmp --
Сравнение первых n символов строк без учета регистра, безопасное для
данных в двоичной форме
- strncmp --
Сравнение первых n символов строк без учета регистра, безопасное для данных в двоичной форме
- strpbrk --
Ищет в строке любой символ из заданного набора
- strpos --
Возвращает позицию первого вхождения подстроки
- strrchr --
Находит последнее вхождение подстроки
- strrev -- Переворачивает строку
- strripos --
Возвращает позицию последнего вхождения подстроки без учета регистра
- strrpos --
Возвращает позицию последнего вхождения символа
- strspn --
Возвращает длину участка в начале строки, соответствующего маске
- strstr --
Находит первое вхождение подстроки
- strtok -- Разбивает строку
- strtolower -- Преобразует строку в нижний регистр
- strtoupper -- Преобразует строку в верхний регистр
- strtr -- Преобразует заданные символы
- substr_compare --
Безопасное для обработки данных в двоичной форме сравнение 2 строк со
смещением, с учетом или без учета регистра
- substr_count -- Возвращает число вхождений подстроки
- substr_replace -- Заменяет часть строки
- substr -- Возвращает подстроку
- trim --
Удаляет пробелы из начала и конца строки
- ucfirst --
Преобразует первый символ строки в верхний регистр
- ucwords --
Преобразует в верхний регистр первый символ каждого слова в строке
- vfprintf -- Write a formatted string to a stream
- vprintf -- Выводит отформатированную строку
- vsprintf -- Возвращает отформатированную строку
- wordwrap --
Выполняет перенос строки на данное количество символов с
использованием символа разрыва строки.
Функции обработки строк
administrador(ensaimada)sphoera(punt)com
02-Mar-2006 06:10
I've prepared this simple function to obtain a string delimited between tags (not only XML tags!). Anybody needs something like this?.
<?php
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$string = "this [custom] function is useless!!";
echo get_string_between($string,"[","]");
?>
more functions at http://www.sphoera.com
SteveRusin
24-Feb-2006 11:00
The functions below:
function beginsWith( $str, $sub )
function endsWith( $str, $sub )
Are correct, but flawed. You'd need to use the === operator instead:
function beginsWith( $str, $sub ) {
return ( substr( $str, 0, strlen( $sub ) ) === $sub );
}
function endsWith( $str, $sub ) {
return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}
Otherwise, endsWith would return "foobar.0" ends with ".0" as well as "0" or "00" or any amount of zeros because numerically .0 does equal 0.
navarr at gmail dot com
20-Dec-2005 06:24
stripos for PHP4.x
<?php
function stripos($haystack,$needle) {
return strpos(strtoupper($haystack),strtoupper($needle));
}
?>
dkflbk at nm dot ru
11-Dec-2005 08:58
I needed str2bin() function for one of my project, so if some one else is want to use it, have fun :)
<?php
function str2bin($str, $mode=0) {
$out = false;
for($a=0; $a < strlen($str); $a++) {
$dec = ord(substr($str,$a,1));
$bin = '';
for($i=7; $i>=0; $i--) {
if ( $dec >= pow(2, $i) ) {
$bin .= "1";
$dec -= pow(2, $i);
} else {
$bin .= "0";
}
}
if ( $mode == 0 ) $out .= $bin;
if ( $mode == 1 ) $out .= $bin . " ";
if ( $mode == 2 ) $out[$a] = $bin;
}
return $out;
}
?>
admin at fivestarbuy dot com
21-Oct-2005 09:18
This example lets you parse an unparsed strings variables. Warning: This could cause security leaks if you allow users to pass $variables through this engine. I recommend only using this for your Content Management System.
<?
$mytime=time();
$mydog="My Dog Ate My PHP!";
$s1 = 'Hyphen Variable Preserving: $mytime, and $mydog';
echo "Before: <br><br>$s1<br><br>";
$vardata=get_defined_vars();
$s1 = StrParse($s1,$vardata);
echo "After: <br><br>$s1";
function StrParse($str,$vardata) {
$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
$myvar=$getvarkeys[$x];
$ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;
}
?>
14-Oct-2005 08:24
Updated; used to test for input as an array, should have been a string, added some validation of the input while I was at it. Enjoy.
<?php
function dirTreeToArray( $path = "./", $style="0" ) {
if ( !is_string($path) or !($style==0 or $style==1) ) die("Improper arguments in function dirTreeToArray(string \$path, \$style = {0, 1})");
else {
$path = trim($path);
$path = str_replace("\\", "/", $path);
if( '/' == $path{strlen($path)-1} || '\'' == $path{strlen($path)-1} ) $path = substr($path, 0, strlen($path)-1);
}
$tree = array();
$arrayPointer = & $tree;
if ( $handle = opendir($path) ) {
while ( $fileName = readdir($handle) ) {
if ( $fileName != "." and $fileName != ".." ) {
$newPath = "$path/$fileName"; if ( is_dir($newPath) ) {
$dummyPointer = & $arrayPointer; if ( $style == 0 ) $arrayPointer = & $arrayPointer[$fileName]; elseif ( $style == 1 ) $arrayPointer = & $arrayPointer[]; $arrayPointer = dirTreeToArray($newPath, $style); if ( $style == 1 ) sort($arrayPointer); $arrayPointer = & $dummyPointer; }
elseif ( is_file($newPath) ) $arrayPointer[] = $fileName; }
}
return $tree;
}
else die("Failed to open directory $path in function dirTreeToArray(string \$path, \$style = {0, 1})");
}
?>
tim_meredith at s4s dot org
13-Oct-2005 01:32
--Convert MSWord Quotes--
Use this before any conversion to HTML entities or characters to clean up a form entry cut and pasted from MSWord.
function fixword($scratch)
{
$start=chr(226).chr(128);
$word=array();$fixword=array();
$word[]=$start.chr(152);$fixword[]="'";
$word[]=$start.chr(153);$fixword[]="'";
$word[]=$start.chr(156);$fixword[]="\"";
$word[]=$start.chr(157);$fixword[]="\"";
return str_replace($word, $fixword, $scratch);
}
webmaster at cafe-clope dot net
13-Aug-2005 04:40
A comprehensive concatenation function, that works with array and strings
<?php
function str_cat() {
$args = func_get_args() ;
foreach($args as $key => $arg) {
if(is_array($arg)) {
if(!isset($dim))
$dim = count($arg) ;
elseif($dim != count($arg))
return FALSE ;
$args[$key] = array_values($arg) ;
}
}
if(isset($dim)) {
$result = array() ;
for($i=0;$i<$dim;$i++) {
$result[$i] = '' ;
foreach($args as $arg)
$result[$i] .= ( is_array($arg) ? $arg[$i] : $arg ) ;
}
return $result ;
} else {
return implode($args) ;
}
}
?>
A simple example :
<?php
str_cat(array(1,2,3), '-', array('foo' => 'foo', 'bar' => 'bar', 'noop' => 'noop')) ;
?>
will return :
Array (
[0] => 1-foo
[1] => 2-bar
[2] => 3-noop
)
More usefull :
<?php
$myget = $_GET ; $myget['foo'] = 'b a r' ; $myget = str_cat(array_keys($myget), '=', array_map('rawurlencode', array_values($myget))) ;
$querystring = implode(ini_get('arg_separator.output'), $myget)) ;
?>
will return a valid querystring with some values changed.
Note that <?php str_cat('foo', '&', 'bar') ; ?> will return 'foo&bar', while <?php str_cat(array('foo'), '&', 'bar') ; ?> will return array(0 => foo&bar)
t0russ at gmail dot com
14-Jun-2005 10:38
to kristin at greenaple dot on dot ca:
thanx for sharing.
your function in recursive form proved to be slightly faster and it returns false (as it should) when the character is not found instead of number 0:
<?php
function strnposr($haystack, $needle, $occurance, $pos = 0) {
return ($occurance<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurance-1,strpos($haystack, $needle, $pos) + 1);
}
?>
rh at richardhoward dot net
05-Jun-2005 11:41
<?php
define('STR_SYBASE', false);
class Str {
function gpc2sql($gpc, $maxLength = false)
{
return Str::pure2sql(Str::gpc2pure($gpc), $maxLength);
}
function gpc2html($gpc, $maxLength = false)
{
return Str::pure2html(Str::gpc2pure($gpc), $maxLength);
}
function gpc2pure($gpc)
{
if (ini_get('magic_quotes_sybase'))
$pure = str_replace("''", "'", $gpc);
else $pure = get_magic_quotes_gpc() ? stripslashes($gpc) : $gpc;
return $pure;
}
function html2pure($html)
{
return html_entity_decode($html);
}
function html2sql($html, $maxLength = false)
{
return Str::pure2sql(Str::html2pure($html), $maxLength);
}
function pure2html($pure, $maxLength = false)
{
return $maxLength ? htmlentities(substr($pure, 0, $maxLength))
: htmlentities($pure);
}
function pure2sql($pure, $maxLength = false)
{
if ($maxLength) $pure = substr($pure, 0, $maxLength);
return (STR_SYBASE)
? str_replace("'", "''", $pure)
: addslashes($pure);
}
function sql2html($sql, $maxLength = false)
{
$pure = Str::sql2pure($sql);
if ($maxLength) $pure = substr($pure, 0, $maxLength);
return Str::pure2html($pure);
}
function sql2pure($sql)
{
return (STR_SYBASE)
? str_replace("''", "'", $sql)
: stripslashes($sql);
}
}
?>
james dot d dot baker at gmail dot com
27-May-2005 10:45
<?php
function sentenceCase($s){
$str = strtolower($s);
$cap = true;
for($x = 0; $x < strlen($str); $x++){
$letter = substr($str, $x, 1);
if($letter == "." || $letter == "!" || $letter == "?"){
$cap = true;
}elseif($letter != " " && $cap == true){
$letter = strtoupper($letter);
$cap = false;
}
$ret .= $letter;
}
return $ret;
}
?>
php at moechofe dot com
26-Apr-2005 06:34
<?php
function str_match( $str, $match )
{
$return = '';
if( eregi( '(.*)', $match, $class ) )
{
$match = '['.$regs[1].']';
for( $i=0; $i<strlen($str); $i++ )
if( ereg( '['.$class[1].']', $str[$i] ) )
$return .= $str{$i};
return $return;
}
else return false;
}
if( ! empty($_REQUEST['a']) )
$_REQUEST['a'] = str_match( $_REQUEST['a'], 'a-zA-Z0-9' );
else
$_REQUEST['a'] = 'default';
?>
Pommef
19-Mar-2005 01:15
Example: Give me everything up to the fourth occurance of '/'.
<?php
$haystack = "/home/username/www/index.php";
$needle = "/";
function strnpos($haystack, $needle, $occurance, $pos = 0) {
$res = implode($needle,$haystack);
$res = array_slice($res, $pos, $occurance);
return explode ($needle,$res);
}
?>
kristin at greenapple dot on dot ca
02-Jan-2005 08:32
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.
strnpos() - Find the nth position of needle in haystack.
<?php
function strnpos($haystack, $needle, $occurance, $pos = 0) {
for ($i = 1; $i <= $occurance; $i++) {
$pos = strpos($haystack, $needle, $pos) + 1;
}
return $pos - 1;
}
?>
Example: Give me everything up to the fourth occurance of '/'.
<?php
$haystack = "/home/username/www/index.php";
$needle = "/";
$root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4));
echo $root_dir;
?>
Returns: /home/username/www
Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!
20-Dec-2004 08:31
In response to hackajar <matt> yahoo <trot> 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.
andy a t onesandzeros d o t biz
09-Nov-2004 02:54
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. :)
// returns true if $str begins with $sub
function beginsWith( $str, $sub ) {
return ( substr( $str, 0, strlen( $sub ) ) == $sub );
}
// return tru if $str ends with $sub
function endsWith( $str, $sub ) {
return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
}
// trims off x chars from the front of a string
// or the matching string in $off is trimmed off
function trimOffFront( $off, $str ) {
if( is_numeric( $off ) )
return substr( $str, $off );
else
return substr( $str, strlen( $off ) );
}
// trims off x chars from the end of a string
// or the matching string in $off is trimmed off
function trimOffEnd( $off, $str ) {
if( is_numeric( $off ) )
return substr( $str, 0, strlen( $str ) - $off );
else
return substr( $str, 0, strlen( $str ) - strlen( $off ) );
}
[tab!]
27-Oct-2004 12:29
//
// string strtrmvistl( string str, [int maxlen = 64],
// [bool right_justify = false],
// [string delimter = "<br>\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.
//
function strtrmvistl($str, $maxlen = 64, $right_justify = false, $delimter = "<br>\n") {
if(($len = strlen($str = chop($str))) > ($maxlen = max($maxlen, 12))) {
$newstr = substr($str, 0, $maxlen - 3);
if($len > ($maxlen - 3)) {
$endlen = min(($len - strlen($newstr)), $maxlen - 3);
$newstr .= "..." . $delimter;
if($right_justify)
$newstr .= str_pad('', $maxlen - $endlen - 3, ' ');
$newstr .= "..." . substr($str, $len - $endlen);
}
return($newstr);
}
return($str);
}
terry dot greenlaw at logicalshift dot com
11-Aug-2004 10:52
Here's a simpler "simplest" way to toggle through a set of 1..n colors for web backgrounds:
<?php
$colours = array('#000000', '#808080', '#A0A0A0', '#FFFFFF');
$color = next($colors) or $color = reset($colors);
?>
The code doesn't need to know anything about the number of elements being cycled through. That way you won't have to tracking down all the code when changing the number of colors or the color values.
| |