Обработка строк

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

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

Содержание

  • addcslashes — Экранирует cтроку слэшами в стиле языка 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 — Преобразует текст на иврите из логической кодировки в визуальную с преобразованием перевода строки
  • hex2bin — Преобразует шестнадцатеричные данные в двоичные
  • html_entity_decode — Преобразует все HTML-сущности в соответствующие символы
  • htmlentities — Преобразует все возможные символы в соответствующие HTML-сущности
  • htmlspecialchars_decode — Преобразует специальные HTML-сущности обратно в соответствующие символы
  • htmlspecialchars — Преобразует специальные символы в HTML-сущности
  • implode — Объединяет элементы массива в строку
  • join — Псевдоним implode
  • lcfirst — Преобразует первый символ строки в нижний регистр
  • 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 в 8-битовую строку
  • quoted_printable_encode — Кодирует 8-битную строку в с помощью метода quoted-printable
  • quotemeta — Экранирует специальные символы
  • rtrim — Удаляет пробелы (или другие символы) из конца строки
  • setlocale — Устанавливает настройки локали
  • sha1_file — Возвращает SHA1-хэш файла
  • sha1 — Возвращает SHA1-хэш строки
  • similar_text — Вычисляет степень похожести двух строк
  • soundex — Возвращает ключ soundex для строки
  • sprintf — Возвращает отформатированную строку
  • sscanf — Разбирает строку в соответствии с заданным форматом
  • str_getcsv — Выполняет разбор CSV-строки в массив
  • 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 — Удаляет экранирование символов
  • stristr — Регистро-независимый вариант функции strstr
  • strlen — Возвращает длину строки
  • strnatcasecmp — Сравнение строк без учета регистра с использованием алгоритма "natural order"
  • strnatcmp — Сравнение строк с использованием алгоритма "natural order"
  • 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 — Записывает отформатированную строку в поток
  • vprintf — Выводит отформатированную строку
  • vsprintf — Возвращает отформатированную строку
  • wordwrap — Переносит строку по указанному количеству символов

Коментарии

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');

// Get a colour
$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.
2004-08-12 01:52:56
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
//
// 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);
}
2004-10-27 15:29:09
http://php5.kiev.ua/manual/ru/ref.strings.html
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 ) );
}
2004-11-09 16:54:25
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
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.
2004-12-20 22:31:47
http://php5.kiev.ua/manual/ru/ref.strings.html
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($haystack0strnpos($haystack$needle4));
   
    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!
2005-01-02 10:32:44
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
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); 
    } 
?>
2005-03-19 15:15:56
http://php5.kiev.ua/manual/ru/ref.strings.html
<?php
 
/*
  * str_match
  *
  * return a string with only cacacteres defined in a expression return false if the expression is not valid
  *
  * @param $str string the string
  * @param $match the expression based on the class definition off a PCRE regular expression.
  *   the '[', ']', '\' and '^' at class start need to be escaped.
  *   like : -a-z0-9_@.
  */
 
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;
  }

 
/*
  * example
  * accept only alphanum caracteres from the GET/POST parameters 'a'
  */

 
if( ! empty($_REQUEST['a']) )
   
$_REQUEST['a'] = str_match$_REQUEST['a'], 'a-zA-Z0-9' );
  else
   
$_REQUEST['a'] = 'default';
?>
2005-04-26 09:34:26
http://php5.kiev.ua/manual/ru/ref.strings.html
<?php
/*
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.
*/

function sentenceCase($s){
   
$str strtolower($s);
   
$cap true;
   
    for(
$x 0$x strlen($str); $x++){
       
$letter substr($str$x1);
        if(
$letter == "." || $letter == "!" || $letter == "?"){
           
$cap true;
        }elseif(
$letter != " " && $cap == true){
           
$letter strtoupper($letter);
           
$cap false;
        }
       
       
$ret .= $letter;
    }
   
    return 
$ret;
}
?>
2005-05-27 13:45:58
http://php5.kiev.ua/manual/ru/ref.strings.html
<?php
/**
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']);
*/

//This sets SQL escaping to use slashes; for Sybase(/MSSQL)-style escaping
// ( ' --> '' ), set to true.
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($pure0$maxLength))
                          : 
htmlentities($pure);
    }
    function 
pure2sql($pure$maxLength false)
    {
        if (
$maxLength$pure substr($pure0$maxLength);
        return (
STR_SYBASE)
               ? 
str_replace("'""''"$pure)
               : 
addslashes($pure);
    }
    function 
sql2html($sql$maxLength false)
    {
       
$pure Str::sql2pure($sql);
        if (
$maxLength$pure substr($pure0$maxLength);
        return 
Str::pure2html($pure);
    }
    function 
sql2pure($sql)
    {
        return (
STR_SYBASE)
               ? 
str_replace("''""'"$sql)
               : 
stripslashes($sql);
    }
}
?>
2005-06-05 14:41:12
http://php5.kiev.ua/manual/ru/ref.strings.html
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);
}
?>
2005-06-14 13:38:26
http://php5.kiev.ua/manual/ru/ref.strings.html
A comprehensive concatenation function, that works with array and strings

<?php
function str_cat() {
 
$args func_get_args() ;
   
 
// Asserts that every array given as argument is $dim-size.
  // Keys in arrays are stripped off.
  // If no array is found, $dim stays unset.
 
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) ;
    }
  }
       
 
// Concatenation
 
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 // retrieving previous $_GET values
$myget['foo'] = 'b a r' // changing one value
$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)
2005-08-13 19:40:18
http://php5.kiev.ua/manual/ru/ref.strings.html
--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);
}
2005-10-13 16:32:35
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
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
/*----------        Directory Tree to Array        ----------//
  Takes base directory, returns an associative array
       containing each directory name as an associative key
       and each file as an indexed entry in the appropriate
       directory.
  If no path is provided, it uses the current directory
  If $style == 1, it will return a sorted, non-associative
       array

  By Peter Dolan
  www.peterd.net
  Updated 2005-10-12

  Use it as much as you like for whatever
  For my own entertainment, please let me know if you do
//-----------------------------------------------------------*/
function dirTreeToArray$path "./"$style="0" ) {
     if ( !
is_string($path) or !($style==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($path0strlen($path)-1);
     }
     
$tree = array();
     
$arrayPointer = & $tree;
   if ( 
$handle opendir($path) ) {
       while ( 
$fileName readdir($handle) ) {
             if ( 
$fileName != "." and $fileName != ".." ) {
                       
$newPath "$path/$fileName";        // Used for testing directory or file property
                 
if ( is_dir($newPath) ) {
                   
$dummyPointer = & $arrayPointer;        // Save the current pointer
                     
if ( $style == $arrayPointer = & $arrayPointer[$fileName];    // Drop the pointer into a subdirectory
                     
elseif ( $style == $arrayPointer = & $arrayPointer[];        // Drop the pointer into a subdirectory
                     
$arrayPointer dirTreeToArray($newPath$style);            // Process the new subdirectory
                   
if ( $style == sort($arrayPointer);    // Sort it if we're in a non-associative mode
                     
$arrayPointer = & $dummyPointer;        // Bring the pointer back up a level
               
}
                 elseif ( 
is_file($newPath) ) $arrayPointer[] = $fileName;    // Enter the files
           
}
       }
               return 
$tree;
   }
   else die(
"Failed to open directory $path in function dirTreeToArray(string \$path, \$style = {0, 1})");
}
?>
2005-10-14 11:24:01
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
to: james dot d dot baker at gmail dot com

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

http://php.net/ucfirst
http://php.net/ucwords
2005-10-17 18:27:35
http://php5.kiev.ua/manual/ru/ref.strings.html
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!";

# Your Parsing String:
$s1 'Hyphen Variable Preserving: $mytime, and $mydog';
echo 
"Before: <br><br>$s1<br><br>";

# Remember, wherever you define this, it will not be defined GLOBAL into the function
# which is why we define it here. Defining it global could lead to security issues.
$vardata=get_defined_vars();

# Parse the string
$s1 StrParse($s1,$vardata);

echo 
"After: <br><br>$s1";

function 
StrParse($str,$vardata) {
# Takes a string, or piece of data, that contains PHP Variables
 
 # For example, unparsed variables like:  Test using time: $mytime
 # This example shows $mytime, and not the actual variable value.
 # The end result shows the actual variable value of $mytime.

 # This is useful for building a content management system,
 # and directing your variables into your content data,
 # where content is stored in a file or database, unparsed.
 # Of course this could slow down page loads, but it's a good way
 # to parse data from current variables into your loaded new data
 # making it compatible.
 
# Then the variables are replaced with the actual variable..
$getvarkeys=array_keys($vardata);
$ret=$str;
for (
$x=0$x count($getvarkeys); $x++) {
   
$myvar=$getvarkeys[$x];
   
#echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
   
$ret=str_replace('$' $myvar$vardata[$myvar], $ret);
}
return 
$ret;

}

?>
2005-10-21 12:18:13
http://php5.kiev.ua/manual/ru/ref.strings.html
I needed str2bin() function for one of my project, so if some one else is want to use it, have fun :)

<?php
/**
 *    Returns an ASCII string containing 
 *    the binary representation of the input data .
**/
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";
            }
        }
       
/* Default-mode */
       
if ( $mode == $out .= $bin;
       
/* Human-mode (easy to read) */
       
if ( $mode == $out .= $bin " ";
       
/* Array-mode (easy to use) */
       
if ( $mode == $out[$a] = $bin;
    }
    return 
$out;
}
?>
2005-12-11 10:58:04
http://php5.kiev.ua/manual/ru/ref.strings.html
stripos for PHP4.x

<?php
 
function stripos($haystack,$needle) {
    return 
strpos(strtoupper($haystack),strtoupper($needle));
  }
?>
2005-12-20 20:24:48
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
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.
2006-02-24 13:00:47
http://php5.kiev.ua/manual/ru/ref.strings.html
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,"[","]");
// must return "custom";
?>
more functions at http://www.sphoera.com
2006-03-02 08:10:50
http://php5.kiev.ua/manual/ru/ref.strings.html
In responce to James Baker's sencence case function.
Great function however i would make one slight variation being that it doesn't take into account the fact that a capital is required after a new paragraph so i modified it to check for /r and /n as follows:
<?PHP
/*/ Author : James Baker /*/
function sentenceCase($s){
   
$str strtolower($s);
   
$cap true;
 
   for(
$x 0$x strlen($str); $x++){
       
$letter substr($str$x1);
       if(
$letter == "." || $letter == "!" || $letter == "?" || $letter == "\n" || $letter == "\r"){
           
$cap true;
       }elseif(
$letter != " " && $cap == true){
           
$letter strtoupper($letter);
           
$cap false;
       }
     
       
$ret .= $letter;
   }
 
   return 
$ret;
}
?>
2006-07-19 03:01:17
http://php5.kiev.ua/manual/ru/ref.strings.html
Sometimes when converting integers to strings, it looks better to have the number spelled out. I wrote this function that converts integers from -999 to 999 into spelled out strings:

function int2str($int=0){
 $doOnes=true;
 $neg=$int<0?true:false;
 $int=abs(round($int));
 $str='';
 switch(strlen($int)){
  case 1:$int='0'.$int;
  case 2:$int='0'.$int;
  case 3:$int.='';break;
  default:return $int;
 }
 switch($int{0}){
  case 1:$str.='one-hundred-';break;
  case 2:$str.='two-hundred-';break;
  case 3:$str.='three-hundred-';break;
  case 4:$str.='four-hundred-';break;
  case 5:$str.='five-hundred-';break;
  case 6:$str.='six-hundred-';break;
  case 7:$str.='seven-hundred-';break;
  case 8:$str.='eight-hundred-';break;
  case 9:$str.='nine-hundred-';break;
 }
 switch($int{1}){
  case 1:
   switch($int{2}){
    case 0:$str.='ten-';break;
    case 1:$str.='eleven-';break;
    case 2:$str.='twelve-';break;
    case 3:$str.='thirteen-';break;
    case 4:$str.='fourteen-';break;
    case 5:$str.='fifteen-';break;
    case 6:$str.='sixteen-';break;
    case 7:$str.='seventeen-';break;
    case 8:$str.='eighteen-';break;
    case 9:$str.='nineteen-';break;
   }
   $doOnes=false;
  break;
  case 2:$str.='twenty-';break;
  case 3:$str.='thirty-';break;
  case 4:$str.='forty-';break;
  case 5:$str.='fifty-';break;
  case 6:$str.='sixty-';break;
  case 7:$str.='seventy-';break;
  case 8:$str.='eighty-';break;
  case 9:$str.='ninety-';break;
 }
 if($doOnes){
  switch($int{2}){
   case 1:$str.='one-';break;
   case 2:$str.='two-';break;
   case 3:$str.='three-';break;
   case 4:$str.='four-';break;
   case 5:$str.='five-';break;
   case 6:$str.='six-';break;
   case 7:$str.='seven-';break;
   case 8:$str.='eight-';break;
   case 9:$str.='nine-';break;
 }}
 $str=substr($str,0,-1);
 if($neg){
  $str='negative '.$str;
 }
 if($int=='000'){
  $str='zero';
 }
 return $str;
}

Hope this helps someone,
-Blayde
2006-07-19 13:52:49
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
I think that
administrador(ensaimada)sphoera(punt)com's function is
too complicated. It's easier with regular expressions.
So I made this function, it isn't really the same,
it's even better because it returns an array with all the 
matches found
If there are no matches, false is returned.

<?php
// bool/array str_between( string str, string
start_strstring end_str )
function 
str_between($str,$start,$end) {
  if (
preg_match_all('/' preg_quote($start) . '(.*?)' preg_quote($end) . '/',$str,$matches)) {
   return 
$matches[1];
  }
 
// no matches
 
return false;
}
?>

Enjoy
2006-07-27 11:17:00
http://php5.kiev.ua/manual/ru/ref.strings.html
Here's an easier way to find nth...

function nth($numbex){
  if ($numbex%10 == 1 && $numbex%100 != 11) $sth='st';
  elseif ($numbex%10 == 2 && $numbex%100 != 12) $sth='nd';
  elseif ($numbex%10 == 3 && $numbex%100 != 13) $sth='rd';
  else $sth = 'th';
  return $sth;
}

there is is no need to check if the user has entered a non-integer as we may be using this function for expressing variables as well eg. ith value of x , nth root of z ,etc...
2006-07-30 06:16:42
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
Well for you egold users out ther I wrote this to just return the balance ONLY
If anyone knows a better way to write this lemme know as im a novice

    function _GetBalance($from, $frompass) {
   $defined_vars = get_defined_vars();

   $_url = 'https://www.e-gold.com/acct/balance.asp';

        $_url_p = "AccountID=" . $from . "&PassPhrase=" . $frompass ."";
           $ch = curl_init();

   curl_setopt($ch, CURLOPT_POST,1);
   curl_setopt($ch, CURLOPT_POSTFIELDS,$_url_p);
   curl_setopt($ch, CURLOPT_URL,$_url);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
   curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
   $content = curl_exec ($ch);

   curl_close ($ch);
$content=strtolower($content);
$content=strstr($content,"</select></font></th></form></tr>");
$content=strip_tags($content);
$content=strrev($content);
$content=strstr($content,"eseht :eton");
$content=str_replace("eseht :eton","",$content);
$content=ltrim($content);
$content=rtrim($content);
$content=substr($content,0,11);
$content=strrev($content);
$content=ltrim($content);

   return $content;

    }
2006-08-02 14:00:20
http://php5.kiev.ua/manual/ru/ref.strings.html
An update to admin at fivestarbuy dot com's StrParse. Since php5.2.x the occurance of an object in the vardata will cause a "Catchable fatal error". Previously it has failed silently, so I added nullification of present objects. 
I also updated comments to be more specific, I hope that's ok with you, admin at fivestarbuy dot com:

<?php
function StrParse($str,$vardata) {

# Variables present in $str is replaced by values of variables in $vardata
# typical use: 
# $vardata = get_defined_vars();
# $str = some template code with variables present.
# uncomment the echo line to debug.

$getvarkeys=array_keys($vardata);
$ret=$str;
for (
$x=0$x count($getvarkeys); $x++) {
   
$myvar=$getvarkeys[$x];
   if(
is_object($vardata[$myvar])) $vardata[$myvar] = null;
   
#echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
   
$ret=str_replace('$' $myvar$vardata[$myvar], $ret);
}
return 
$ret;
}
?>
2007-03-25 19:23:05
http://php5.kiev.ua/manual/ru/ref.strings.html
[Editor's Note: Remember that number names are locale-specific. Thus in the US 1,000,000,000 is called a billion, while in other countries this might be different (ie. miljard in Dutch). This function provides support only for the US locale]

If you want to convert a number, (int or float) to full spoken text, then you can use my num2text converter, at http://bloople.net/num2text

Examples:
40000 => forty thousand
1,796,706 => one million, seven hundred and ninety-six thousand, seven hundred and six.

If works for positive an negative integers/floats/doubles. The code is only a page long, and you don't have to install any modules or anything.

I hope this comes in handy for somebody!
2007-05-22 21:05:31
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
Here is a truly random string generator it uses the most common string functions it will work on anywhere.

<?php
   
function random_string($max 20){
       
$chars explode(" ""a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9");
        for(
$i 0$i $max$i++){
           
$rnd array_rand($chars);
           
$rtn .= base64_encode(md5($chars[$rnd]));
        }
        return 
substr(str_shuffle(strtolower($rtn)), 0$max);
    }
?>
2007-06-17 20:59:43
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
In responce to mike here is a better random string function

<?php
   
function random_string($max 20){
       
$chars "abcdefghijklmnopqrstuvwxwz0123456789_";
        for(
$i 0$i $max$i++){
           
$rand_key mt_rand(0strlen($chars));
           
$string  .= substr($chars$rand_key1);
        }
        return 
str_shuffle($string);
    }
?>
2007-07-10 09:44:28
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
Regarding the code for the function beginsWith($str, $sub), I found that it has problems when only one character is present after the string searched for. I found that this works better instead:

<?php
function beginsWith($str$sub) {
    return (
strncmp($str$substrlen($sub)) == 0);
}
?>
2007-07-26 20:10:04
http://php5.kiev.ua/manual/ru/ref.strings.html
This took me quite some time to figure out and it is so obvious. So, I hope it helps someone out there like it would have helped me if I would have found it on this page:

I wanted to read a binary file and write it out with some modified bytes with their hex values. The easiest way I could come up with was the following:

read the file line by line, e.g. 400 bytes and then chuck it into an array with e.g.

<?php
$handle 
= @fopen("/path/to/file.bin""r");
if (
$handle) {
    while (!
feof($handle)) {
       
$buffer[] = fgets($handle400);
    }
   
fclose($handle);
   
$buffer[0][0] = chr(hexdec("FF")); // set the first byte to 0xFF
}
// write out the file from the array ...
?>

One could write a function for that, so that One can write a string of bytes. Don't have time for this now but you should get the idea.
2008-01-07 05:18:40
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
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
2008-03-19 20:06:52
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
If you want to indent a block of text with $level tabs, you can use

function str_indent($level, $text) {
    return str_repeat("\t", $level).str_replace("\n", "\n".str_repeat("\t", $level), $text);
}
2008-03-28 04:43:14
http://php5.kiev.ua/manual/ru/ref.strings.html
In reference to Moe... best random string function
<?php
function random_string($l 10){
   
$c "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";
    for(;
$l 0;$l--) $s .= $c{rand(0,strlen($c))};
    return 
str_shuffle($s);
}
?>
2008-08-04 07:10:52
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.

Works in PHP >= 5.

(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)

<?php

// Returns all of $haystack up to (but excluding) the $n_occurrence occurrence of $needle. Therefore:
//        If there are < $n_occurrence occurrences of $needle in $haystack, the entire string will be returned.
//        If there are >= $n_occurrence occurrences of $needle in $haystack, the returned string will end before the $n_occurrence'th needle.
// This function only makes sense for $n_occurrence >= 1
function nsubstr($needle$haystack$n_occurrence)
{
   
// After exploding by $needle, every entry in $arr except (possibly) part of the last entry should have its content returned.
   
$arr explode($needle,$haystack,$n_occurrence);
   
// Examine last entry in $arr. If it contains $needle, cut out all text except for the text before $needle.
   
$last count($arr) - 1;
   
$pos_in_last strpos($arr[$last],$needle);
   
    if (
$pos_in_last !== false)
       
$arr[$last] = substr($arr[$last],0,$pos_in_last);
   
    return 
implode($needle,$arr);
}

$string 'd24jkdslgjldk2424jgklsjg24jskgldjk24';

print 
'S:  ' $string '<br>';
print 
'1: ' nsubstr('24',$string,1) . '<br>';
print 
'2: ' nsubstr('24',$string,2) . '<br>';
print 
'3: ' nsubstr('24',$string,3) . '<br>';
print 
'4: ' nsubstr('24',$string,4) . '<br>';
print 
'5: ' nsubstr('24',$string,5) . '<br>';
print 
'6: ' nsubstr('24',$string,6) . '<br>';
print 
'7: ' nsubstr('24',$string,7) . '<br>';

/*
// 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 <br>, and then you can use this function to only return text up to the N'th <br>.

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().

See example:

<?php

$text 
'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.';

$wrapped_text wordwrap($text,100,'<br>',true);

$three_lines nsubstr('<br>',$wrapped_text,3);

print 
'<br><br>' $three_lines;

$four_lines nsubstr('<br>',$wrapped_text,4);

print 
'<br><br>' $four_lines;

/*
prints:

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

*/

?>
2008-11-19 19:33:07
http://php5.kiev.ua/manual/ru/ref.strings.html
get the intersection of two strings; may not have optimal performance

<?php
function mb_string_intersect($string1$string2$minChars 5)
{
   
assert('$minChars > 1');

   
$string1 trim($string1);
   
$string2 trim($string2);

   
$length1 mb_strlen($string1);
   
$length2 mb_strlen($string2);

    if (
$length1 $length2) {
       
// swap variables, shortest first

       
$string3 $string1;
       
$string1 $string2;
       
$string2 $string3;

       
$length3 $length1;
       
$length1 $length2;
       
$length2 $length3;

        unset(
$string3$length3);
    }

    if (
$length2 255) {
        return 
null// to much calculation required
   
}

    for (
$l $length1$l >= $minChars; --$l) { // length
       
for ($i 0$ix $length1 $l$i <= $ix; ++$i) { // index
           
$substring1 mb_substr($string1$i$l);
           
$found mb_strpos($string2$substring1);
            if (
$found !== false) {
                return 
trim(mb_substr($string2$foundmb_strlen($substring1)));
            }
        }
    }

    return 
null;
}
echo 
mb_string_intersect("hello spencer""hey spencer how are you?"); // output "spencer"
?>
2009-10-14 08:01:41
http://php5.kiev.ua/manual/ru/ref.strings.html
Автор:
Get the intersection of two strings using array_intersect

<?php

function string_intersect($string1$string2)
{
   
$array1 $array2 = array();

    for(
$i 0$j 0$s1_len strlen($string1), $s2_len strlen($string2);($i $s1_len) || ($j $s2_len); $i++, $j++) {
        if(
$i $s1_len) {
           
$array1[] = $string1[$i];
        }
        if(
$j $s2_len) {
           
$array2[] = $string2[$j];
        }
    }

    return 
implode(''array_intersect($array1$array2));
}

?>

For more advanced comparison you can use array_uintersect as well.
2012-02-08 23:58:00
http://php5.kiev.ua/manual/ru/ref.strings.html

    Поддержать сайт на родительском проекте КГБ