레이블이 PHP인 게시물을 표시합니다. 모든 게시물 표시
레이블이 PHP인 게시물을 표시합니다. 모든 게시물 표시

2009년 5월 14일 목요일

멀티바이트로 인코딩된 utf-8의 디코딩

죽음..
$str = "JCD비비안체크롱남방";

if (preg_match('/&#([0-9]{1,});/', $str))
    $str = mb_decode_numericentity($str, array(0x0, 0x10000, 0, 0xfffff), 'UTF-8');

echo iconv('utf-8','cp949', $str );
echo "\n----\n";

모뇽~~~

2009년 3월 4일 수요일

내가 만든 초성 검색 알고리즘

입력: ㄴㄱ [검색]

mysql> select name from products
    -> where (substring(name,1,1) > '나' and substring(name,1,1) <'다')
    -> and (substring(name,2,1) > '가' and substring(name,2,1) <'나');

결과: 농구티

모 그닥 어렵진 않았음, 이걸 패턴 매칭으로 해도 되는데 귀챦음
노가다가 짱임

2009년 2월 12일 목요일

htmlspecialchars -> htmlspecialchars_decode 사용

htmlspecialchars로 변경된 데이터를 encode / decode하는 경우
php version 5 이상에서는
htmlspecialchars_decode 가 기본 function이지만 없는 경우 만들어 써야 함.

function htmlspecialchars_decode($string, $quote_style = null)
{
// Sanity check
if (!is_scalar($string)) {
user_error('htmlspecialchars_decode() expects parameter 1 to be string, ' .
gettype($string) . ' given', E_USER_WARNING);
return;
}

if (!is_int($quote_style) && $quote_style !== null) {
user_error('htmlspecialchars_decode() expects parameter 2 to be integer, ' .
gettype($quote_style) . ' given', E_USER_WARNING);
return;
}

// Init
$from = array('&amp;', '&lt;', '&gt;');
$to = array('&', '<', '>');

// The function does not behave as documented
// This matches the actual behaviour of the function
if ($quote_style & ENT_COMPAT || $quote_style & ENT_QUOTES) {
$from[] = '&quot;';
$to[] = '"';

$from[] = '&#039;';
$to[] = "'";
}

return str_replace($from, $to, $string);
}

2008년 12월 3일 수요일

[php] 마지막 한 글자 제거..

$str = 'abc,ddd,eee,fff,"; // 이와 같은 문자가 있을때 마지막의 ,를 삭제 하고 싶은 경우가 있다.

// 이딴식으로 해봤는데 다른 좋은 방법 없나?
$str = substr( $str , 0, strlen( $str ) -1 );

// 패턴 매칭을 사용해?
// 이런것도 되긴 한데 뭐가 더 좋을까? 아무래도 substr이 더 빠를 듯..ㅋㅋㅋ
$str = preg_replace ( "/[\,]\$/", '', $str );



2008년 10월 31일 금요일

php에서 cURL 설치

http://curl.haxx.se/docs/install.html


php를 컴파일 새로 해야 할 것 같으다.

일단 cURL을 다운 받도록 한다.

7.19.0 을 다운 받는 중

압축을 푼 뒤 ./configure실행

/usr/local/include/curl/curlbuild.h 에 cURL 설치 함 make test는 통과하지 못 함.

/usr/local/include/curl 이 path_home 임


open-ssl도 필요함

필요한거 많구만~ 일단은 ./configure --without-ssl 을 사용해서 ssl을 off함


php를 새로 깔아야 하나? 흠흠..

configure할때 cURL이랑 뭐 extension을 설치 해야 하는거 아닌가?

./configure --with-apxs=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql --with-curl=/usr/local/include/curl

ok 성공 mysql쪽 오류가 나서 directory를 설정해줌

사용자 삽입 이미지

php는 적절히 알아서 잘 깔아야 함. global 키워드를 사용하고 있었는데 재 설치후는 사용이 안됨 다시 설정해봐야 할 듯

php.ini를 손 좀 보고 아파치 재 실행하니 잘 나옴

/usr/local/lib/php.ini 가 있음

사용자 삽입 이미지



2008년 10월 22일 수요일

리스트 하단의 페이지 인덱스 구하는 로직..

자체 제작함 버그가 있으려나?

<?
$tot_page = 40;  // 전체 페이지
$mypage   = 7;   // 현재 페이지

// 차이 구함
$end_page   = $mypage <= 5 ?  ( ($mypage + 5) - ( $mypage-5 ) < $tot_page ?  ($mypage + 5) - ( $mypage-5 ) : $tot_page) : ($mypage+5
 < $tot_page ? $mypage+5 : $tot_page);
$begin_page   = $mypage <= 5 ?  1 : ( $mypage + 5 < $tot_page ?  $mypage - 4 : ($mypage-4)-( $mypage+5 - $tot_page ) );

for ( $i = $begin_page; $i < $end_page; $i++ )
    echo "$i\n";
?>

2008년 10월 11일 토요일

php에서 추가로 공부할 내용

MVC 패턴 : CakePHP, Symfony Project, Zend, Codelgniter ...
XHTML, OOP , 자바스크립트 프레임웍(jquery, Prototype, GWT, Dojo, ExJS) ...
파일 업로더 : Swfuploader, YUI Uploader ...
리치 텍스트박스 에디터 : TinyMCE, YUI Simple Editor ...

2008년 10월 8일 수요일

2008년 10월 7일 화요일

nhn이 구글 흉내를 내다~ 큐브리드 db를 오픈소스화 하다..

얼마전 nhn에서 db회사를 하나 인수 했다는 소식을 들은 적이 있다, 그 회사의 이름은 큐브리드 아직 큐브리드가 어떤 회사 인지는 모르지만 nhn에서는 이 dbms를 오픈소스화 한다고 한다.
리눅스 버젼이 있나 모르겠네, 얼마전에 설치한 우분투에 깔아 설치해 봐야겠다.
ㅎㅎㅎ
기대 된다.

사실 mySQL도 좋긴 하지만 아무래도 한글 문제도 있고 버젼이 변경될때 마다 과거에 저장했던 한글이 깨져버리는 바람에 대략 난감했던 경험도 있고 해서.

무엇보다 잘은 모르지만 최근 많이 사용되는 php에 대한 지원이 좋지 않을까 하는 기대를 해본다.

큐브리드 공식 홈: http://www.cubrid.com/
공시 정보 링크 http://dart.fss.or.kr/frameForm.do?rcpNo=20080930000293&dcmNo=

2008년 7월 21일 월요일

Worksheet.php 를 사용하여 excel을 생성하고 있다.

숫자가 길어질 경우 뒷 자리가 0000 으로 나와 버리는 문제점이 보고 되었는데 format을 사용하여 수정을 하려고 노력 함

 $this->format = & $workbook->addformat($text);
 $this->format->setNumFormat('0');
등등의 format 셋팅 후


$worksheet->write($i, $j, $val , $this->format);
으로 값을 저장할때 $this->format을 추가해 포맷을 설정해줌 하지만 아무리 해도 통하지 않음
결국 engine을 손을 봐야 했음

Spreadsheet/Excel/Writer/Worksheet.php 를 열어보면 write라는 function이 있다.
 function write($row, $col, $token, $format = 0)
    {
        // Check for a cell reference in A1 notation and substitute row and column
        /*if ($_[0] =~ /^\D/) {
            @_ = $this->_substituteCellref(@_);
    }*/


        // Match number
        if (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/",$token)) {
            //return $this->writeNumber($row,$col,$token,$format);
            // 바꿔 버림...잘됨
            return $this->writeString($row,$col,$token,$format);
        }
        // Match http or ftp URL
        elseif (preg_match("/^[fh]tt?p:\/\//",$token)) {
            return $this->writeUrl($row, $col, $token, '', $format);
        }
        // Match mailto:
        elseif (preg_match("/^mailto:/",$token)) {
            return $this->writeUrl($row, $col, $token, '', $format);
        }
        // Match internal or external sheet link
        elseif (preg_match("/^(?:in|ex)ternal:/",$token)) {
            return $this->writeUrl($row, $col, $token, '', $format);
        }
        // Match formula
        elseif (preg_match("/^=/",$token)) {
            return $this->writeFormula($row, $col, $token, $format);
        }
        // Match formula
        elseif (preg_match("/^@/",$token)) {
            return $this->writeFormula($row, $col, $token, $format);
        }
        // Match blank
        elseif ($token == '') {
            return $this->writeBlank($row,$col,$format);
        }
        // Default: match string
        else {
            return $this->writeString($row,$col,$token,$format);
        }
    }

2008년 4월 3일 목요일

Json사용을 위한 셋팅2

pear에서 json관련 라이브러리를 설치 하면
json_encode와 json_decode를 아무데서나 call할 수 있는 환경이 된다.
하..지..만 설치가 되지 않는 경우도 있다.


<?php
if ( !function_exists('json_decode'
) ){
    function
json_decode($content, $assoc=false
){
                require_once
'Services/JSON.php'
;
                if (
$assoc
){
                   
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE
);
        } else {
                   
$json = new Services_JSON
;
                }
        return
$json->decode($content
);
    }
}

if ( !
function_exists('json_encode'
) ){
    function
json_encode($content
){
                require_once
'Services/JSON.php'
;
               
$json = new Services_JSON
;
               
        return
$json->encode($content
);
    }
}
?>
참조 사이트: http://pear.php.net/pepr/pepr-proposal-show.php?id=198


2008년 1월 22일 화요일

DOM TO ARRAY SAMPLE

<?php

function dom_to_simple_array($domnode, &$array) {
  $array_ptr = &$array;
  $domnode = $domnode->firstChild;
  while (!is_null($domnode)) {
    if (! (trim($domnode->nodeValue) == "") ) {
      switch ($domnode->nodeType) {
        case XML_TEXT_NODE: {
          $array_ptr['cdata'] = $domnode->nodeValue;
          break;
        }
        case XML_ELEMENT_NODE: {
          $array_ptr = &$array[$domnode->nodeName][];
          if ($domnode->hasAttributes() ) {
            $attributes = $domnode->attributes;
            if (!is_array ($attributes)) {
              break;
            }
            foreach ($attributes as $index => $domobj) {
              $array_ptr[$index] = $array_ptr[$domobj->name] = $domobj->value;
            }
          }
          break;
        }
      }
      if ( $domnode->hasChildNodes() ) {
        dom_to_simple_array($domnode, $array_ptr);
      }
    }
    $domnode = $domnode->nextSibling;
  }
}

  # now, let's make a sample string containing some XML
  $strXMLData = "<contacts>
       <contact>
         <name>
           John Doe
         </name>
         <phone>
           123-456-7890
         </phone>
       </contact>
       <contact>
         <name>
           Mary Smiley
         </name>
         <phone>
           567-890-1234
         </phone>
       </contact>
     </contacts>";

  # create a DOM tree xml object (hierarchical array) from
  # this XML string
  $domdoc = new DOMDocument;
  $domdoc->loadXML($strXMLData);

  # now simplify the DOM array into a very simple array structure

  # first, create an empty array to be filled with your
  # simplified array result..
  $aData = array();

  # now, pass the dom document and your empty array to the
  # converter function.
  dom_to_simple_array($domdoc, $aData);

  # now $aData contains your simplified array, so print it out
?><html>
<body>
<p>there are <? echo count($aData['contacts'][0]['contact']); ?>
contacts</p>
<p>the 2nd contact's phone number is
<?echo $aData['contacts'][0]['contact'][1]['phone'][0]['cdata']; ?>
</p>
<hr />
<p>Here is the raw array structure:</p>
<pre>
<? print_r($aData); ?>
</pre>
</body>
</html>

2008년 1월 10일 목요일

[xml] in php

xml sample
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="345435">
<name>John Smith</name>
</employee>
</employees>
xml_decode
<?php

// The raw post body is available in the variable $HTTP_RAW_POST_DATA
$employees = xml_decode($HTTP_RAW_POST_DATA);

// Get the employee element
$employee = $employees->employee[0];

// Get the id attribute
$id = $employee['id'];

// Get the name
$name = $employee->name->toString();

?>


xml_encode
$var = array('name' => "Smith", 'address' => array('line1' => 'This lane', 'line2' => 'Somewhere'));
echo xml_encode($var,  "employee");


xml_encode source
function xml_encode($array, $indent=false, $i=0) {
if(!$i) {
$data = '<?xml version="1.0"?>'.($indent?"\r\n":'').'<root>'.($indent?"\r\n":'');
} else {
$data = '';
}

foreach($array as $k => $v) {
if(is_numeric($k)) {
$k = 'item';
}

$data .= ($indent?str_repeat("\t", $i):'').'<'.$k.'>';

if(is_array($v)) {
$data .= ($indent?"\r\n":'').xml_encode($v, $indent, ($i + 1)).($indent?str_repeat("\t", $i):'');
} else {
$data .= $v;
}

$data .= '</'.$k.'>'.($indent?"\r\n":'');
}

if(!$i) {
$data .= '</root>';
}

return $data;






2007년 11월 29일 목요일

[ ] 의 개수

preg_match_all("|[\[](.*)[\]]|U", $macro, $matches);

        // 매크로 케이스 체크
        if ( count($matches[0]) > 1 )
        {
                $macro_case = 1; // ex) <packs>[product_name][options][qty]
                $arr_macro = $matches[1];
        }

2007년 11월 12일 월요일

날짜 연산....관련

두 날짜 사이의 차를 연산
  intval((strtotime("2005-01-10")-strtotime("2005-01-02"))/86400)    =>     8

strtotime 사용...
    strtotime("+3 day")

2007년 10월 30일 화요일

buffer를 사용해 출력하기

ob_start를 call해서 output buffer를 생성한다.
buffer를 종료하는 방법은 2가지가 있다.
ob_end_flush()를 사용하는 방법과 ob_end_clean()을 사용하는 방법이다.
ob_end_flush()를 사용할 경우 그동안의 print결과를 모두 출력한다.

ob_end_clean()을 사용할 경우 결과를 출력하지 않고 buffer의 내용을 삭제 한다.

open된 buffer는 스크립트가 종료될 경우 자동으로 end_flush된다.

<?php
    ob_start
();
    print
"Hello First!\n"
;
   
ob_end_flush
();

   
ob_start
();
    print
"Hello Second!\n"
;
   
ob_end_clean
();

   
ob_start
();
    print
"Hello Third!\n"
;
?>


결과
Hello First!
Hello Third!

2007년 10월 29일 월요일

[pattern] 숫자 리스트 중 마지막의 문자 제거

// 마지막 문자 제거
        $pattern = "/(\D+)$/";
        $replace = "";
        $transno_list = preg_replace( $pattern, $replace, $transno_list );

2007년 10월 26일 금요일

Dynamic library 설치

1. Module 설치

2. php환경 설정
/usr/local/php/lib/php.ini 를 open함

Module이 설치된 Directory설정
extension_dir = "/usr/local/php/lib/php/extensions"

Module 설정
특정한 디렉터리위치에 대한 정보는 셋팅하지 않는다
extension=json.so

3. apache 설정
/usr/local/apache2/modules 에 extension 파일을 넣어 줬음 원래 이렇게 하는게 아닌것 같지만 그냥 그렇게 했음 귀챦음..ㅋㅋ

apache2의 httpd.conf에 이런놈이 있긴 하네...좋네~
LoadModule php5_module          modules/libphp5.so

글면 단가? 이렇게 간단한데 왜 메뉴얼을 못 찾았을까? 제길...너무 쉬워서 아무도 안 알려 주나?

[php-json] 설치

다운 받았지..
http://aurore.net/projects/php-json/


앞축을 풀어야 함
root계정으로 들어가서 냅다 압축을 풀었음
# tar -jxvf php-json-ext-1.2.1.tar.bz2

쓰여진 대로 설치함
./configure
make
make install


* configure시 php-config가 없다고 하는 경우가 있다.

./configure --with-php-config=/usr/local/php/bin/php-config


extension=json.so 를 php.ini / php.d에 설정해주라고 하는데 어떻게 하는거지?

간단한 예제 작성
<?
$val = array("abc" => 12,
             "foo" => "bar",
             "bool0" => false,
             "bool1" => true,
             "arr" => array(1, 2, 3, null, 5),
             "float" => 1.2345
            );
$output = json_encode($val);
echo $output."\n";

?>
~            

작동 안됨
Unable to load dynamic library './json.so'

json.so 를 /usr/local/lib 로 가져다 넣음
php.ini에
; Directory in which the loadable extensions (modules) reside.
extension_dir = "./"
extension_dir = "/usr/local/php/lib/php/extensions"

extension=json.so 를 셋팅 해 줌

오에~
dk
결과:
php json.php
{"abc":12,"foo":"bar","bool0":false,"bool1":true,"arr":[1,2,3,null,5],"float":1.2345}