PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

AddCSlashes> <stream_wrapper_unregister
Last updated: Sun, 25 Nov 2007

view this page in

문자열 함수

소개

이 함수들은 문자열을 여러가지 방법으로 다룹니다. 좀 더 특화된 섹션으로 정규표현식과 URL 다루기 섹션이 있습니다.

문자열이 어떻게 작동하는지, 특히 작은 따옴표, 큰 따옴표, 이스케이프 시퀀스의 사용에 대해서 매뉴얼 타입 섹션의 문자열 부분을 참고하십시오.

요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.

설치

이 함수들은 설치하지 않아도 사용할 수 있습니다; PHP 코어의 일부입니다.

예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

CRYPT_SALT_LENGTH integer
CRYPT_STD_DES integer
CRYPT_EXT_DES integer
CRYPT_MD5 integer
CRYPT_BLOWFISH integer
HTML_SPECIALCHARS (integer)
HTML_ENTITIES (integer)
ENT_COMPAT (integer)
ENT_QUOTES (integer)
ENT_NOQUOTES (integer)
CHAR_MAX (integer)
LC_CTYPE (integer)
LC_NUMERIC (integer)
LC_TIME (integer)
LC_COLLATE (integer)
LC_MONETARY (integer)
LC_ALL (integer)
LC_MESSAGES (integer)
STR_PAD_LEFT (integer)
STR_PAD_RIGHT (integer)
STR_PAD_BOTH (integer)

참고

더 강력하게 문자열을 다루고 조작하는 함수를 원한다면, POSIX 정규표현식 함수펄 호환 정규표현식 함수를 살펴보십시오.

Table of Contents

  • AddCSlashes — C 형식으로 문자열에 슬래쉬를 덧붙입니다.
  • addslashes — 문자열에 슬래쉬를 덧붙입니다.
  • bin2hex — 바이너리 데이터를 16진수 표현으로 바꿉니다.
  • chop — rtrim의 별칭.
  • chr — 특정 문자를 반환합니다.
  • chunk_split — 문자열을 작은 조각으로 나눕니다.
  • convert_cyr_string — 키릴 문자셋을 다른 것으로 변환합니다.
  • convert_uudecode — Decode a uuencoded string
  • convert_uuencode — Uuencode a string
  • count_chars — 문자열 안에 사용한 문자에 대한 정보를 반환합니다.
  • crc32 — 문자열의 crc32값을 계산합니다.
  • crypt — 단방향 문자열 암호화(해슁).
  • echo — 하나 이상의 문자열을 출력합니다.
  • explode — 문자열을 주어진 문자열을 기준으로 분리합니다.
  • fprintf — 문자열을 형식화하여 스트림에 기록합니다.
  • get_html_translation_table — htmlspecialchars와 htmlentities에서 사용하는 변환표를 반환합니다.
  • hebrev — 논리 헤브라이어 텍스트를 표시 텍스트로 변환합니다.
  • hebrevc — 개행 문자를 포함하여 논리 헤브라이어 텍스트를 표시 텍스트로 변환합니다.
  • html_entity_decode — 모든 HTML 엔티티를 해당하는 문자로 변환합니다.
  • htmlentities — 해당하는 모든 문자를 HTML 엔티티로 변환합니다.
  • htmlspecialchars_decode — Convert special HTML entities back to characters
  • htmlspecialchars — 특수 문자를 HTML 엔터티로 변환합니다.
  • implode — 문자열로 배열 요소를 결합합니다.
  • join — implode의 별칭.
  • levenshtein — 두 문자열 사이의 Levenshtein distance를 계산합니다.
  • localeconv — 숫자 형식화 정보를 얻습니다.
  • ltrim — 문자열 시작 부분의 공백을 제거합니다.
  • md5_file — 주어진 파일명의 md5 해쉬를 계산합니다.
  • md5 — 문자열의 md5 해쉬를 계산합니다.
  • metaphone — 문자열의 메타폰 키를 계산합니다.
  • money_format — Formats a number as a currency string
  • nl_langinfo — Query language and locale information
  • nl2br — 문자열의 모든 줄바꿈 앞에 HTML 줄바꿈 태그를 삽입합니다.
  • number_format — Format a number with grouped thousands
  • ord — 문자의 아스키 값을 반환합니다.
  • parse_str — 문자열을 처리하여 변수를 생성합니다.
  • print — 문자열을 출력합니다.
  • printf — 형식화한 문자열을 출력합니다.
  • quoted_printable_decode — 인용되어 있는 출력 가능 문자열을 8비트 문자열로 변환합니다.
  • quotemeta — 메타 문자를 인용합니다.
  • rtrim — 문자열 끝 부분의 공백을 제거합니다.
  • setlocale — 지역적보를 지정한다.
  • sha1_file — 파일의 sha1 해쉬를 계산합니다.
  • sha1 — 문자열의 sha1 해쉬를 계산합니다.
  • similar_text — 두 문자열 간의 유사성을 계산합니다.
  • soundex — 문자열의 soundex 키를 계산합니다.
  • sprintf — 형식화한 문자열을 반환합니다.
  • sscanf — 문자열을 형식에 따라 처리합니다.
  • str_getcsv — Parse a CSV string into an array
  • 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 — "natural order" 알고리즘을 이용한 대소문자를 구별하지 않는 문자열 비교.
  • strnatcmp — "natural order" 알고리즘을 이용한 문자열 비교
  • strncasecmp — 대소문자를 구별하지 않는 처음 n 문자의 이진 호환 문자열 비교
  • strncmp — 처음 n 문자의 이진 호환 문자열 비교
  • strpbrk — Search a string for any of a set of characters
  • strpos — 문자열이 처음 나타나는 위치를 찾습니다.
  • strrchr — 문자열에서 문자가 마지막으로 나오는 부분을 찾습니다.
  • strrev — 문자열을 뒤집습니다.
  • strripos — 문자열에서 대소문자 구별 없이 문자열이 나타나는 마지막 위치를 찾습니다.
  • strrpos — 문자열에서 마지막 문자의 위치를 찾습니다.
  • strspn — 마스크에 매칭되는 초기 세그먼트의 길이를 찾는다.
  • strstr — 문자열이 처음으로 나타나는 부분을 찾습니다.
  • strtok — 문자열을 토큰화 합니다.
  • strtolower — 문자열을 소문자로 만듭니다.
  • strtoupper — 문자열을 대문자로 만듭니다.
  • strtr — 특정 문자를 번역한다.
  • substr_compare — Binary safe comparison of 2 strings from an offset, up to length characters
  • substr_count — 부분문자열의 수를 센다
  • substr_replace — 문자열의 일부를 치환한다.
  • substr — 문자열의 일부를 반환한다.
  • trim — 문자열의 처음과 끝에 있는 공백을 제거한다.
  • ucfirst — 문자열의 처음 글자를 대문자로 만든다.
  • ucwords — 문자열에 있는 각 단어의 처음 글자를 대문자로 바꾼다.
  • vfprintf — Write a formatted string to a stream
  • vprintf — Output a formatted string
  • vsprintf — Return a formatted string
  • wordwrap — 정지문자를 이용해 주어진 수 만큼의 문자를 래핑한다.


AddCSlashes> <stream_wrapper_unregister
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
문자열
Salomon
28-Mar-2008 03:43
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);
}
Verdauga
19-Mar-2008 07:06
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
geek dot de at gmail dot com
07-Jan-2008 03:18
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($handle, 400);
    }
   
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.
m
26-Jul-2007 05:10
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, $sub, strlen($sub)) == 0);
}
?>
Moe
10-Jul-2007 06:44
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(0, strlen($chars));
           
$string  .= substr($chars, $rand_key, 1);
        }
        return
str_shuffle($string);
    }
?>
mike &#34;eyes&#34; moe
17-Jun-2007 05:59
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);
    }
?>
bloopletech at gmail dot com
22-May-2007 06:05
[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!
benjamin at webbutvecklarna dot se
25-Mar-2007 05:23
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;
}
?>
beggining pro
02-Aug-2006 11:00
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;

    }
admin at rotarymulundeast dot org
30-Jul-2006 03:16
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...
heavyraptor
27-Jul-2006 08:17
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_str, string 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
da (dot) blayde (a t) gmail (dot) com
19-Jul-2006 10:52
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
mickycole at hotmail dot com
19-Jul-2006 12:01
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, $x, 1);
       if(
$letter == "." || $letter == "!" || $letter == "?" || $letter == "\n" || $letter == "\r"){
          
$cap = true;
       }elseif(
$letter != " " && $cap == true){
          
$letter = strtoupper($letter);
          
$cap = false;
       }
     
      
$ret .= $letter;
   }
 
   return
$ret;
}
?>
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,"[","]");
// must return "custom";
?>
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
/**
 *    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 == 0 ) $out .= $bin;
       
/* Human-mode (easy to read) */
       
if ( $mode == 1 ) $out .= $bin . " ";
       
/* Array-mode (easy to use) */
       
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!";

# 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;

}

?>
17-Oct-2005 03:27
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
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
/*----------        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==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";        // Used for testing directory or file property
                
if ( is_dir($newPath) ) {
                  
$dummyPointer = & $arrayPointer;        // Save the current pointer
                    
if ( $style == 0 ) $arrayPointer = & $arrayPointer[$fileName];    // Drop the pointer into a subdirectory
                    
elseif ( $style == 1 ) $arrayPointer = & $arrayPointer[];        // Drop the pointer into a subdirectory
                    
$arrayPointer = dirTreeToArray($newPath, $style);            // Process the new subdirectory
                  
if ( $style == 1 ) 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})");
}
?>
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() ;
   
 
// 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)
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
/**
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($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
/*
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, $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
 
/*
  * 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';
?>
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');

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

AddCSlashes> <stream_wrapper_unregister
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites