사이트 내 전체검색
PHP
[문법] PCRE 정규표현식 고급예제
로빈아빠
https://cmd.kr/php/36 URL이 복사되었습니다.

본문

PCRE 정규표현식 고급예제


http://kr2.php.net/manual/en/ref.pcre.php
http://kr2.php.net/manual/en/reference.pcre.pattern.syntax.php
http://kr2.php.net/manual/en/reference.pcre.pattern.modifiers.php

1. 엑셀에서 textarea 로 붙여넣기 한 데이터 파싱
<?php
$_POST['excel'] = <<<TEXT
가나 다\t\taaa\t"asdf
""zxcv"""""
1234\tccc\t"aa\tbb"\t
TEXT;
$cnt = preg_match_all('@("(.*?(?<!")("")*)"(?!")|([^\t]+))?(\t|(\r?\n))@s', $_POST['excel'], $matches);
$j = 0;
for($i = 0; $i < $cnt; $i ++) {
     $cols[$j][] = str_replace('""', '"', ($matches[2][$i] != '') ? $matches[2][$i] : $matches[4][$i]);
     if($matches[6][$i] != '') {
         $j ++;
     }
}
print_r($cols);
?>
Array
(
     [0] => Array
         (
             [0] => 가나 다
             [1] =>
             [2] => aaa
             [3] => asdf
"zxcv""
         )

     [1] => Array
         (
             [0] => 1234
             [1] => ccc
             [2] => aa bb
         )

)

2. form 내용 파싱
<?php
$text = <<<TEXT
<html>
<body>
<form method="post" action="modify.php">
<input type="hidden" name="seq" value = "12" />
<input name="bname" type= 'hidden' value="qna" />
<input value="asdf" type=text name = "subject" />
<textarea name="contents">voiajsodjfw</textarea>
</form>
TEXT;
if(!preg_match('@<form .*?</form>@si', $text, $matches)) {
    exit;
}
$form = $matches[0];
$cnt = preg_match_all('@(<input (.*?)/?>|<textarea .*?name\s*=\s*(([\'"])(.*?)\4|([^\s>]+)).*?>(.*?)</textarea>)@si', $form, $matches);
for($i = 0; $i < $cnt; $i ++) {
    if($matches[2][$i] != '') {
        $cnt2 = preg_match_all('@([a-z]+)\s*=\s*(([\'"])(.*?)\3|([^\s]+))@i', $matches[2][$i], $values);
        for($j = 0; $j < $cnt2; $j ++) {
    $input->{$values[1][$j]} = ($values[4][$j] != '') ? $values[4][$j] : $values[5][$j];
        }
    } else {
        $input->name = ($matches[5][$i] != '') ? $matches[5][$i] : $matches[6][$i];
        $input->value = $matches[7][$i];
    }
    $inputs[] = $input;
    unset($input);
}
print_r($inputs);
?>
Array
(
     [0] => stdClass Object
         (
             [type] => hidden
             [name] => seq
             [value] => 12
         )

     [1] => stdClass Object
         (
             [name] => bname
             [type] => hidden
             [value] => qna
         )

     [2] => stdClass Object
         (
             [value] => asdf
             [type] => text
             [name] => subject
         )

     [3] => stdClass Object
         (
             [name] => contents
             [value] => voiajsodjfw
         )

)

3. CSV 값이 있는 필드만 파싱
<?php
$text = ',,,,감자, , ,고구마, ,오이, ,,,';
$cols = preg_split('/[\s,]+/', preg_replace('/^[\s,]+|[\s,]+$/', '', $text));
print_r($cols);
?>
Array
(
     [0] => 감자
     [1] => 고구마
     [2] => 오이
)

4. iso3166 표준 매칭으로 URL 에 a 태그 걸기
<?php
$text = <<<TEXT
가나다http://xenosi.de/ 라마바
홈페이지xenosi.de는 아무것도 없다.
스쿨:phpschool.com은 222.122.158.253이다.
개인회선은 80 포트가 막혀서 gaein.com:8080으로 연결한다.
//phpschool.com 이 절대경로인것 알고 있던사람?
TEXT;
echo autolink($text);

function autolink($html)
{
    return preg_replace_callback('@((https?|ftps?|ed2k|mmst?)://|//)?((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|([a-z\d\-\.]+(\.(com|net|org|af|al|dz|as|ad|ao|ai|aq|ag|ar|am|aw|au|at|az|bs|bh|bd|bb|by|be|bz|bj|bm|bt|bo|ba|bw|bv|br|io|vg|bn|bg|bf|bi|kh|cm|ca|cv|ky|cf|td|cl|cn|cx|cc|co|km|cd|cg|ck|cr|ci|cu|cy|cz|dk|dj|dm|do|ec|eg|sv|gq|er|ee|et|fo|fk|fj|fi|fr|gf|pf|tf|ga|gm|ge|de|gh|gi|gr|gl|gd|gp|gu|gt|gn|gw|gy|ht|hm|va|hn|hk|hr|hu|is|in|id|ir|iq|ie|il|it|jm|jp|jo|kz|ke|ki|kp|kr|kw|kg|la|lv|lb|ls|lr|ly|li|lt|lu|mo|mk|mg|mw|my|mv|ml|mt|mh|mq|mr|mu|yt|mx|fm|md|mc|mn|ms|ma|mz|mm|na|nr|np|an|nl|nc|nz|ni|ne|ng|nu|nf|mp|no|om|pk|pw|ps|pa|pg|py|pe|ph|pn|pl|pt|pr|qa|re|ro|ru|rw|sh|kn|lc|pm|vc|ws|sm|st|sa|sn|cs|sc|sl|sg|sk|si|sb|so|za|gs|es|lk|sd|sr|sj|sz|se|ch|sy|tw|tj|tz|th|tl|tg|tk|to|tt|tn|tr|tm|tc|tv|vi|ug|ua|ae|gb|um|us|uy|uz|vu|ve|vn|wf|eh|ye|zm|zw))))(:\d+)?(/[^ <>\r\n]+)?)@im', 'autolink_callback', $html);
}
function autolink_callback($matches)
{
    $link = '';
    if($matches[2] != '') {
        $link .= $matches[1];
    } else {
        $link .= 'http://';
    }
    $link .= $matches[3];
    return '<a href="'.$link.'" target="_blank">'.$matches[0].'</a>';
}
?>
가나다<a href="http://xenosi.de" target="_blank">http://xenosi.de</a>/ 라마바
홈페이지<a href="http://xenosi.de" target="_blank">xenosi.de</a>는 아무것도 없다.
스쿨:<a href="http://phpschool.com" target="_blank">phpschool.com</a>은 <a href="http://222.122.158.253" target="_blank">222.122.158.253</a>이다.
개인회선은 80 포트가 막혀서 <a href="http://gaein.com:8080" target="_blank">gaein.com:8080</a>으로 연결한다.
<a href="http://phpschool.com" target="_blank">//phpschool.com</a> 이 절대경로인것 알고 있던사람?

댓글목록

등록된 댓글이 없습니다.

PHP
871 (1/18P)

Search

Copyright © Cmd 명령어 3.139.103.122