|
użytkowników online: 15
|
OPINIE UŻYTKOWNIKÓW
|
Po wysłaniu do Dariusza problemu jeszcze nie opisanego w poradach, odpowiedź pojawia się na stronach już po 24 godzinach. To jedna z najważniejszych zalet serwisu! Za około 100 złotych rocznie mam profesjonalnego i doświadczonego konsultanta od technologii internetowych! Polecam serwis z poradami każdemu webmasterowi, niezależnie od stażu pracy i umiejętności.
Paweł Kowalski
grupa hiperMEDIA.pl
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
CXXI. String Functions
These functions all manipulate strings in various ways. Some more
specialized sections can be found in the regular expression and
URL handling sections.
For information on how strings behave, especially with regard to
usage of single quotes, double quotes, and escape sequences, see
the Strings entry in
the Types section of the
manual.
Do zbudowania tego rozszerzenia nie są wymagane
żadne zewnętrzne biblioteki. By używać tych funkcji, nie trzeba niczego instalować.
Są one częścią jądra PHP.
Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy
rozszerzenie jest dokompilowane do PHP, lub załadowane dynamicznie przy starcie.
- Spis treści
- addcslashes -- Quote string with slashes in a C style
- addslashes -- Quote string with slashes
- bin2hex --
Convert binary data into hexadecimal representation
- chop -- Alias of rtrim()
- chr -- Return a specific character
- chunk_split -- Split a string into smaller chunks
- convert_cyr_string --
Convert from one Cyrillic character set to another
- convert_uudecode --
Decode a uuencoded string
- convert_uuencode --
Uuencode a string
- count_chars --
Return information about characters used in a string
- crc32 -- Calculates the crc32 polynomial of a string
- crypt -- One-way string encryption (hashing)
- echo -- Output one or more strings
- explode -- Split a string by string
- fprintf -- Write a formatted string to a stream
- get_html_translation_table --
Returns the translation table used by
htmlspecialchars() and
htmlentities()
- hebrev --
Convert logical Hebrew text to visual text
- hebrevc --
Convert logical Hebrew text to visual text with newline conversion
- html_entity_decode --
Convert all HTML entities to their applicable characters
- htmlentities --
Convert all applicable characters to HTML entities
- htmlspecialchars_decode --
Convert special HTML entities back to characters
- htmlspecialchars --
Convert special characters to HTML entities
- implode -- Join array elements with a string
- join -- Alias of implode()
- levenshtein --
Calculate Levenshtein distance between two strings
- localeconv -- Get numeric formatting information
- ltrim --
Strip whitespace (or other characters) from the beginning of a string
- md5_file -- Calculates the md5 hash of a given file
- md5 -- Calculate the md5 hash of a string
- metaphone -- Calculate the metaphone key of a string
- money_format -- Formats a number as a currency string
- nl_langinfo --
Query language and locale information
- nl2br --
Inserts HTML line breaks before all newlines in a string
- number_format -- Format a number with grouped thousands
- ord -- Return ASCII value of character
- parse_str -- Parses the string into variables
- print -- Output a string
- printf -- Output a formatted string
- quoted_printable_decode --
Convert a quoted-printable string to an 8 bit string
- quotemeta -- Quote meta characters
- rtrim --
Strip whitespace (or other characters) from the end of a string
- setlocale -- Set locale information
- sha1_file -- Calculate the sha1 hash of a file
- sha1 -- Calculate the sha1 hash of a string
- similar_text --
Calculate the similarity between two strings
- soundex -- Calculate the soundex key of a string
- sprintf -- Return a formatted string
- sscanf --
Parses input from a string according to a format
- str_ireplace --
Case-insensitive version of str_replace().
- str_pad --
Pad a string to a certain length with another string
- str_repeat -- Repeat a string
- str_replace --
Replace all occurrences of the search string with the replacement string
- str_rot13 -- Perform the rot13 transform on a string
- str_shuffle -- Randomly shuffles a string
- str_split --
Convert a string to an array
- str_word_count --
Return information about words used in a string
- strcasecmp --
Binary safe case-insensitive string comparison
- strchr -- Alias of strstr()
- strcmp -- Binary safe string comparison
- strcoll -- Locale based string comparison
- strcspn --
Find length of initial segment not matching mask
- strip_tags -- Strip HTML and PHP tags from a string
- stripcslashes --
Un-quote string quoted with addcslashes()
- stripos --
Find position of first occurrence of a case-insensitive string
- stripslashes --
Un-quote string quoted with addslashes()
- stristr --
Case-insensitive strstr()
- strlen -- Get string length
- strnatcasecmp --
Case insensitive string comparisons using a "natural order"
algorithm
- strnatcmp --
String comparisons using a "natural order" algorithm
- strncasecmp --
Binary safe case-insensitive string comparison of the first n
characters
- strncmp --
Binary safe string comparison of the first n characters
- strpbrk --
Search a string for any of a set of characters
- strpos --
Find position of first occurrence of a string
- strrchr --
Find the last occurrence of a character in a string
- strrev -- Reverse a string
- strripos --
Find position of last occurrence of a case-insensitive string in a string
- strrpos --
Find position of last occurrence of a char in a string
- strspn --
Find length of initial segment matching mask
- strstr -- Find first occurrence of a string
- strtok -- Tokenize string
- strtolower -- Make a string lowercase
- strtoupper -- Make a string uppercase
- strtr -- Translate certain characters
- substr_compare --
Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters
- substr_count -- Count the number of substring occurrences
- substr_replace -- Replace text within a portion of a string
- substr -- Return part of a string
- trim --
Strip whitespace (or other characters) from the beginning and end of a string
- ucfirst -- Make a string's first character uppercase
- ucwords --
Uppercase the first character of each word in a string
- vfprintf -- Write a formatted string to a stream
- vprintf -- Output a formatted string
- vsprintf -- Return a formatted string
- wordwrap --
Wraps a string to a given number of characters using a string
break character
User Contributed Notesnavarr at gmail dot com
21-Dec-2005 03:24
stripos for PHP4.x
<?php
function stripos($haystack,$needle) {
return strpos(strtoupper($haystack),strtoupper($needle));
}
?>
dkflbk at nm dot ru
11-Dec-2005 05: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 06: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;
}
?>
18-Oct-2005 12:27
14-Oct-2005 05: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 10: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
14-Aug-2005 01: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 07: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 08: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 07: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 03: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 10: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 05: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!
21-Dec-2004 05: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 11: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 09: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
12-Aug-2004 07: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.
|