Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-10 01:36
관리 메뉴

zyint's blog

String 본문

예전글들

String

진트­ 2009. 2. 16. 18:28

String

문자열을 표현하며, 길이의 제한이 없다.

PHP는 기본적으로 유니코드를 지원하지 않는다. 단, utf8_encode(), utf8_decode()에서 기본적인 유니코드 기능을 제공한다.

 

Syntax

: Single quoted

문자열을 홑따옴표(')로 묶어서 표현할 수 있다. single qouted된 문자열에 escaped character나 변수가 있어도 해당 값으로 바꿔서 표현하지 않고, 홑따옴표 사이의 문자열 그대로 출력한다.

 

예제코드:

  1. <?php
    echo 'this is a simple string'
    ;

    echo 
    'You can also have embedded newlines in 
    strings this way as it is
    okay to do'
    ;

    // Outputs: Arnold once said: "I'll be back"
    echo 'Arnold once said: "I\'ll be back"'
    ;

    // Outputs: You deleted C:\*.*?
    echo 'You deleted C:\\*.*?'
    ;

    // Outputs: You deleted C:\*.*?
    echo 'You deleted C:\*.*?'
    ;

    // Outputs: This will not expand: \n a newline
    echo 'This will not expand: \n a newline'
    ;

    // Outputs: Variables do not $expand $either
    echo 'Variables do not $expand $either'
    ;
    ?>

 

: Double quoted

 문자열을 곁따옴표(")로 묶어서 표현할 수 있다. 이 경우 곁따옴표로 묶여진 문자열 사이에 있는 escaped charter나 변수의 값으로 바꿔서 표현한다.

 

Escaped characters  

Sequence Meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

 

: Heredoc

Perl에서 사용되던 heredoc 문법(<<<)으로 긴 문자열을 깔끔하게 표현할 수 있도록 하는 방법이다.

문자열의 시작부분과 끝나는 부분에 identifier를 사용자가 설정할 수 있게 한다.

double-qouted에서처럼 변수나 escaped characters를 사용할 수 있다.

 

예제: 기본 heredoc 사용

  1. echo <<<theEnd
  2. line 1
  3. line 2
  4. line 3
  5. theEnd;

 

예제: heredoc 안에서 변수나 escaped character를 사용하는 경우

  1.  <?php
    $str 
    = <<<EOD
    Example of string
    spanning multiple lines
    using heredoc syntax.
    EOD;

    /* More complex example, with variables. */
    class 
    foo
    {
        var 
    $foo
    ;
        var 
    $bar
    ;

        function 
    foo
    ()
        {
            
    $this->foo 'Foo'
    ;
            
    $this->bar = array('Bar1''Bar2''Bar3'
    );
        }
    }

    $foo = new foo
    ();
    $name 'MyName'
    ;

    echo <<<EOT
    My name is "$name". I am printing some $foo->foo
    .
    Now, I am printing some 
    {$foo->bar[1]}
    .
    This should print a capital 'A': \x41
    EOT;
    ?>

출력:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

 

예제: 함수의 파라미터로 들어가는 경우

  1. <?php
    var_dump
    (array(<<<EOD
    foobar!
    EOD
    ));
    ?>
     

출력:

array
 
 0 => string 'foobar!' (length=7)

 

identifier의 규칙

  • identifier의 이름(네이밍) 규칙

    • 이름은 문자나 숫자, '_'로 이루어져야 한다.

    • 이름은 숫자로 시작할 수 없다.

  • identifier 규칙

    • 문자열이 끝나는 부분임을 나타내는 identifier앞에 공백이나, 탭 문자가 들어가면 안된다. 반드시 첫 컬럼에 있어야 한다.

    • 문자열이 끝나는 부분임을 나타내는 identifier와 세미콜론 뒤에 공백이나 탭 문자가 들어가서는 안된다. 반드시 identifier와 세미콜론으로 해당 라인을 끝내야 한다.

    • class member 변수를 초기화 하는데 사용될 수 없다(since PHP 5.3)
      잘못 사용한 예:

  1. <?php
    class foo 
    {
        public 
    $bar 
    = <<<EOT
    bar
    EOT;
    }
    ?>

 

: Nowdoc

 Heredoc과 같이 여러 줄을 표현하지만, single-qouted처럼 문자열 내부에 있는 변수나 escaped characters를 값으로 바꿔서 표현하지 않고 문자열 그대로 출력한다.

heredoc과는 달리 문자열 시작부분의 identifier를 홑따옴표(')로 묶어서 표현한다. e.g.) <<<'EOT'

 

예제: Nowdoc string quoting example

  1. <?php
    $str 
    = <<<'EOD'
    Example of string
    spanning multiple lines
    using nowdoc syntax.
    EOD;

    /* More complex example, with variables. */
    class 
    foo
    {
        public 
    $foo
    ;
        public 
    $bar
    ;

        function 
    foo
    ()
        {
            
    $this->foo 'Foo'
    ;
            
    $this->bar = array('Bar1''Bar2''Bar3'
    );
        }
    }

    $foo = new foo
    ();
    $name 'MyName'
    ;

    echo <<<'EOT'
    My name is "$name". I am printing some $foo->foo.
    Now, I am printing some {$foo->bar[1]}.
    This should not print a capital 'A': \x41
    EOT;
    ?>

출력:

My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

 

Heredoc과는 달리 Nowdoc은 클래스 멤버변수 초기화할때 사용할 수 있다.

예제: nowdoc의 클래스 멤버변수 초기화

  1.  <?php
    class foo 
    {
        public 
    $bar 
    = <<<'EOT'
    bar
    EOT;
    }
    ?>

 

Variable parsing

문자열이 heredoc이나 double qouted일 때 변수가 문자열 사이에 있는 경우, 변수 값으로 바뀌어서 표현된다.

달러 문자($)가 나오면 $뒤의 문자열을 변수명으로 인식하고 해당 변수의 값을 나타낸다. 중괄호({, })로 감싸는 경우 변수의 끝을 명확하게 표현할 수 있다.

 

: Simple syntax

  1. <?php
    $beer 
    'Heineken'
    ;
    echo 
    "$beer's taste is great"
    // works; "'" is an invalid character for variable names
    echo "He drank some $beers";   
    // 동작하지 않음; beer뒤에 s도 변수 이름으로 생각해서 $beers라는 변수 값을 출력함.
    echo "He drank some ${beer}s"
    // works
    echo "He drank some {$beer}s"
    // works
    ?> 

 

  1. <?php
    // These examples are specific to using arrays inside of strings.
    // When outside of a string, always quote array string keys and do not use
    // {braces}.

    // Show all errors
    error_reporting(E_ALL
    );

    $fruits = array('strawberry' => 'red''banana' => 'yellow'
    );

    // Works, but note that this works differently outside a string
    echo "A banana is $fruits[banana]."
    ;

    // Works
    echo "A banana is {$fruits['banana']}."
    ;

    // Works, but PHP는 banana라는 상수값이 정의되어있는지를 찾고, 없을경우 'banana'를 반환한다. 만일 banana라는 상수가 정의되어있다면 엉뚱한 값을 나타낼 수 있다.
    echo "A banana is {$fruits[banana]}."
    ;

    // Won't work, use braces.  This results in a parse error.
    echo "A banana is $fruits['banana']."
    ;

    // Works
    echo "A banana is " $fruits['banana'] . "."
    ;

    // Works
    echo "This square is $square->width meters broad."
    ;

    // Won't work. For a solution, see the complex syntax. 변수 값 뒤에 00을 붙여서 출력하려고 하지만, PHP parser는 width00 이라는 변수를 찾아서 출력하라는 의미로 인식한다.
    echo "This square is $square->width00 centimeters broad."
    ;
    ?>

 

: Complex (curly) syntax

  1. <?php
    // Show all errors
    error_reporting(E_ALL);

    $great 'fantastic';

    // Won't work, outputs: This is { fantastic}
    echo "This is { $great}";

    // Works, outputs: This is fantastic
    echo "This is {$great}";
    echo 
    "This is ${great}";

    // Works
    echo "This square is {$square->width}00 centimeters broad."

    // Works
    echo "This works: {$arr[4][3]}";

    // This is wrong for the same reason as $foo[bar] is wrong  outside a string.
    // In other words, it will still work, but only because PHP first looks for a
    // constant named foo; an error of level E_NOTICE (undefined constant) will be
    // thrown.
    echo "This is wrong: {$arr[foo][3]}"

    // Works. When using multi-dimensional arrays, always use braces around arrays
    // when inside of strings
    echo "This works: {$arr['foo'][3]}";

    // Works.
    echo "This works: " $arr['foo'][3];

    echo 
    "This works too: {$obj->values[3]->name}";

    echo 
    "This is the value of the var named $name{${$name}}";

    echo 
    "This is the value of the var named by the return value of getName(): {${getName()}}";

    echo 
    "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
    ?>

참고: {$} 안에서 함수 호출은 PHP5 부터 지원된다.

 

String을 char 배열로 사용하기

String 문자열을 배열처럼 접근하여 값을 가져오거나, 해당 문자를 수정할 수 있다.

문자열 값을 가지고 있는 변수 이름이 $str라면 $str[42]로 43번째 문자열을 가져올 수 있다.(배열은 0부터 시작한다)

 

  1. <?php
    // Get the first character of a string
    $str 'This is a test.'
    ;
    $first $str[0
    ]; // T

    // Get the third character of a string
    $third $str[2
    ]; // i

    // Get the last character of a string.
    $str 'This is still a test.'
    ;
    $last $str[strlen($str)-1
    ]; // .

    // Modify the last character of a string
    $str 'Look at the sea'
    ;
    $str[strlen($str)-1] = 'e'
    ; // Look at the see

    ?>

 

 

함수 및 연산자

문자열을 서로 합칠 경우 '.'(점) 연산자를 사용한다.

 

관련 함수

 

타입변환

string 형으로 타입을 변환하려면 (string)을 앞에 붙이거나 strval() 함수를 사용한다.

 

타입별 형 변환

  • boolean

    • TRUE 값일 경우 string의 "1",
    • FALSE일 경우 ""(the empty string)으로 변환한다.
  • integer / float: 해당 숫자를 문자열로 변환하여 표현한다.
  • array: "Array"라는문자열만 변환한다.
  • Object

    • PHP 4: "Object"라는 문자열만 반환한다.
    • get_class() 함수로 클래스 이름을 알아낼 수 있다.
  • Resource: "Resource id #1"과 같은 문자열로 변환한다. 1은 PHP runtime때의 해당 리소스의 고유 숫자를 나타낸다
  • NULL: ""로 변환된다.

 

string형을 숫자로의 변환

문자열에서 '.', 'e', 'E' 문자를 가지고 있으면 float 형이고 아니면 integer로 변환한다.

문자열이 숫자로 시작하는 경우 문자를 무시하고 숫자로 반환하지만, 문자로 시작한는 경우 해당 문자열은 0으로 변환된다.

 

예제:

  1. <?php
    $foo 
    "10.5";                
    // $foo is float (11.5)
    $foo "-1.3e3";              
    // $foo is float (-1299)
    $foo "bob-1.3e3";           
    // $foo is integer (1)
    $foo "bob3";                
    // $foo is integer (1)
    $foo "10 Small Pigs";       
    // $foo is integer (11)
    $foo "10.2 Little Piggies"
    // $foo is float (14.2)
    $foo "10.0 pigs " 1;          
    // $foo is float (11)
    $foo "10.0 pigs " 1.0;        
    // $foo is float (11)     
    ?>

 

 

참고자료

 http://www.php.net/manual/kr/language.types.string.php

 PHP와 MySQL : 성공적인 웹 프로그래밍 (3판), pp 71 - heredoc

 

 

 

 

 

이 글은 스프링노트에서 작성되었습니다.

Comments