<?php $text = <<<TEXT $cnt = preg_match_all([\'"])(?P
Array
PCRE 정규표현식 고급예제
<?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 ) )
<?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 ) )
<?php
$text = ',,,,감자, , ,고구마, ,오이, ,,,'; $cols = preg_split('/[\s,]+/', preg_replace('/^[\s,]+|[\s,]+$/', '', $text)); print_r($cols); ?> Array
( [0] => 감자 [1] => 고구마 [2] => 오이 )
<?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> 이 절대경로인것 알고 있던사람?
PCRE 정규표현식 기본기
http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=59162&sca=%B9%AE%B9%FD&sfl=wr_name%7C%7Csubject&stx=%BC%DB%C8%BF%C1%F8&sop=and PCRE 정규표현식 예제로 개념잡기. http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=58121&sca=&sfl=wr_name%7C%7Csubject&stx=%BC%DB%C8%BF%C1%F8&sop=and PCRE 정규표현식 기본기
<?php
preg_match('/\//', '---/---', $matches); echo $matches[0]; ?> /
<?php
echo preg_replace('/^./', '', 'abcd'); ?> bcd
<?php
echo preg_replace('/.$/', '', 'abcd'); ?> abc
<?php
if(!preg_match('/^[1-9]\d*$/', $_GET['no'])) { echo '1 부터 시작하는 수를 적으셔'; exit; } if(!preg_match('/^[a-z]+$/', $_GET['text'])) { echo '영문 소문자만 적으셔'; } ?>
<?php
$text = <<<TEXT 가나다 김삼순 킹왕짱 어쭈구리 abcd TEXT; print_r(preg_split('/[\s\r\n]+/', $text)); ?> Array
( [0] => 가나다 [1] => 김삼순 [2] => 킹왕짱 [3] => 어쭈구리 [4] => abcd ) <?php
$text = <<<TEXT 이름\t진\t선\t미 김태희\t80\t90\t100 송혜교\t100\t100\t98 TEXT; $rows = preg_split('/[\r\n]+/', $text); foreach($rows as $row) { $cols[] = preg_split('/\t/', trim($row)); } print_r($cols); ?> Array
( [0] => Array ( [0] => 이름 [1] => 진 [2] => 선 [3] => 미 ) [1] => Array ( [0] => 김태희 [1] => 80 [2] => 90 [3] => 100 ) [2] => Array ( [0] => 송혜교 [1] => 100 [2] => 100 [3] => 98 ) )
<?php
$text = <<<TEXT <input type="text" name=asdf value="asdf" /> TEXT; $cnt = preg_match_all('@([a-z]+)\s*=\s*"?([a-z]+)@', $text, $matches); unset($matches[0]); print_r($matches); ?> Array
( [1] => Array ( [0] => type [1] => name [2] => value ) [2] => Array ( [0] => text [1] => asdf [2] => asdf ) ) <?php
$text = <<<TEXT <p>asdf <strong>zxcv</strong></p> <p><strong>zxcv</strong> zxcv zxcv</p> TEXT; echo preg_replace('@(<strong>)?zxcv(</strong>)?@', 'qwer', $text); ?> <p>asdf qwer</p>
<p>qwer qwer qwer</p>
<?php
$text = <<<TEXT <a href="a">a</a><a href="b">b</a><a href="c">c</a> TEXT; preg_match('@<a .*>@', $text, $matches); echo $matches[0]."\n"; preg_match('@<a .*?>@', $text, $matches); echo $matches[0]."\n"; ?> <a href="a">a</a><a href="b">b</a><a href="c">c</a>
<a href="a">
PCRE 정규표현식 예제로 개념잡기.
http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=58121&sca=&sfl=wr_name%7C%7Csubject&stx=%BC%DB%C8%BF%C1%F8&sop=and PCRE 정규표현식 예제로 개념잡기.
pattern syntax1. [0-9] 는 \d 로 표현하는것이 편리하다. <?php
if(!isset($_POST['seq']) || !preg_match('/^[1-9]\d*$/', $_POST['seq'])) { // 시퀀스는 1부터 시작하므로 처음은 1-9 이다. header('HTTP/1.1 400'); echo str_repeat('해킹은 사절<br />', 200); exit; } ?>
<?php
$text = 'abcd'; echo preg_replace('/(?=b)./', 'e', $text); // 조건에 맞는곳에서 한글자 가져오기. ?> aecd
(?<=문자) (?<!문자) : 문자열 길이 계산에 반영된다. <?php
$text = 'abcd'; echo preg_replace('/(?<=b)./', 'e', $text); // 조건이 맞는곳 다음 한글자 가져오기. ?> abed
따옴표로 감싼 문자열에 \ 가 있어도 정확하게 뽑아내 보자. <?php
$text = <<<TEXT <script type="text/javascript"> document.body.innerHTML += "<div style=\"font-size:12px; color:white; background-color:black;\">"; document.body.innerHTML += '\'예제 만들기 귀찮네...\''; document.body.innerHTML += "</div>"; TEXT; $cnt = preg_match_all('@(?<!\x5c)([\'"])(.*?)(?<!\x5c)\1@', $text, $matches); print_r($matches[2]); ?> Array
( [0] => text/javascript [1] => <div style=\"font-size:12px; color:white; background-color:black;\"> [2] => \'예제 만들기 귀찮네...\' [3] => </div> ) 5. 줄바꿈이 \r\n 인지 \n 인지 비교하기 귀찮으므로 [\r\n]+ 혹은(\r?\n) 으로 표현하자. <?php
$text = 'abcd가나다라2345'; $cnt = preg_match_all('/./u', $text, $matches); // 글자 단위로 잘라 가져온다. print_r($matches); echo preg_replace('/[^\x{ac00}-\x{d7af}]+/u', '', $text); // 한국어만 남긴다. ?> Array
( [0] => Array ( [0] => a [1] => b [2] => c [3] => d [4] => 가 [5] => 나 [6] => 다 [7] => 라 [8] => 2 [9] => 3 [10] => 4 [11] => 5 ) ) 가나다라
<?php
$text = '가 나 다'; // 나와 다 사이는 묶음빈칸이다. echo preg_replace('/\p{Zs}/u', '', $text); ?> 가나다
이렇듯 문자들을 속성에 따라 그룹으로 나누어 표기할 수 있다. pattern modifier1. /m <?php
$text = <<<TEXT 1. 가 2. 나 3. 다 TEXT; preg_match_all('/(^(\d+)|(.)$)/mu', $text, $matches); // 앞의 수와 뒤의 한글자를 가져온다. print_r($matches[2]); print_r($matches[3]); ?> Array
( [0] => 1 [1] => [2] => 2 [3] => [4] => 3 [5] => ) Array ( [0] => [1] => 가 [2] => [3] => 나 [4] => [5] => 다 ) 2. .* 로 여러줄을 다 매칭할 때는 /s 를 사용한다. <?php
$text = <<<TEXT <a href="http://xenosi.de/" target="_blank" title="송효진의 홈페이지"> 아무것도 없어요. </a> TEXT; preg_match('@<a\s.*?>(.*?)</a>@su', $text, $matches); print_r($matches[1]); ?> 아무것도 없어요. 4. 기본적으로 정규식은 매치되는 표현중 가장 큰 값을 가져온다. <?php
$text = <<<TEXT <a href="http://xenosi.de/" target="_blank" title="송효진의 홈페이지"> 아무것도 없어요. </a> <a href="http://xenosi.de/" target="_blank" title="송효진의 홈페이지"> 아무것도 없어요. </a> TEXT; echo "--1--\n"; preg_match('@<a.*?>(.*)</a>@su', $text, $matches); // 모두 다 가져올 것이다. print_r($matches[1]); echo "--2--\n"; preg_match('@<a.*?>(.*?)</a>@su', $text, $matches); // 가장 간편하고 알아보기 좋다. 추천. print_r($matches[1]); echo "--3--\n"; preg_match('@<a(?U).*>(?U)(.*)</a>@su', $text, $matches); // pattern modifier 식을 부분만 적용하는데 범위를 알아보기가 좋지 않다. print_r($matches[1]); echo "--4--\n"; preg_match('@<a.*>(.*)</a>@Usu', $text, $matches); // 식 전체에 적용된다. print_r($matches[1]); ?> --1--
아무것도 없어요. </a> <a href="http://xenosi.de/" target="_blank" title="송효진의 홈페이지"> 아무것도 없어요. --2-- 아무것도 없어요. --3-- 아무것도 없어요. --4-- 아무것도 없어요. 5. 대소문자 구별 없애는 /i 는 설명하면 손가락 아프다. 응용 예제.<?php
$text = <<<TEXT <a href="http://xenosi.de/" target="_blank" title ="송효진의 홈페이지"> 아무것도 없어요. </a> <a href="http://xenosi.de/?a=&b=나&c=다&d&e" target="_blank" title = "송효진의 홈페이지"> 아무것도 없어요. </a> TEXT; if(preg_match('@<a\s(.*?)>@s', $text, $matches)) { $cnt = preg_match_all('@([^\pZ=]+?)\pZ*=\pZ*([\'"])(.*?)\2@us', $matches[1], $matches2); print_r($matches2[1]); print_r($matches2[3]); } echo preg_replace_callback('@href=([\'"])((https?://[^\?]+\??)?(.*?))\1@', 'urlencode_callback', $text); function urlencode_callback($matches) { return 'href='.$matches[1].$matches[3].preg_replace_callback('/(.*?)=([^&]+)/', 'urlencode_value_callback', $matches[4]).$matches[1]; } function urlencode_value_callback($matches) { return $matches[1].'='.urlencode($matches[2]); } ?> Array
( [0] => href [1] => target [2] => title ) Array ( [0] => http://xenosi.de/ [1] => _blank [2] => 송효진의 홈페이지 ) <a href="http://xenosi.de/" target="_blank" title ="송효진의 홈페이지"> 아무것도 없어요. </a> <a href="http://xenosi.de/?a=%EA%B0%80&b=%EB%82%98&c=%EB%8B%A4&d&e" target="_blank" title = "송효진의 홈페이지"> 아무것도 없어요. </a> 인덱싱을 위한 단어 추출 예제http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=50824&sca=&sfl=wr_name%7C%7Csubject&stx=%BC%DB%C8%BF%C1%F8&sop=and&page=2 끝으로 이 문서를 하일라이팅 하기 위한 소스를 붙이고 마친다.원본글은 첨부파일로 올린다. <?php
$pattern[] = '/&/'; $replacement[] = '&'; $pattern[] = '/</'; $replacement[] = '<'; $pattern[] = '/>/'; $replacement[] = '>'; $pattern[] = '/(\r?\n)/'; $replacement[] = "<br />\n"; $pattern[] = '/\s{4}|\t/'; $replacement[] = ' '; $pattern[] = '@^\*\*(.*)<br />@m'; $replacement[] = '<h3>\1</h3>'; $pattern[] = '@^\*(.*)<br />@m'; $replacement[] = '<h2>\1</h2>'; $pattern[] = '@(https?://[^\s<"]+)@'; $replacement[] = '<a href="\1" target="_blank">\1</a>'; $pattern[] = '@(<\?php<br />.*?\?><br />)@s'; $replacement[] = '<div style="background-color:black; color:white; padding:10px; font-family:GungSuhChe,MonoSpace;">\1</div>'; $pattern[] = '@<-<br />(.*?)-><br />@s'; $replacement[] = '<div style="background-color:#003300; color:white; padding:10px; font-family:GungSuhChe,MonoSpace;">\1</div>'; $pattern[] = '@<#<br />(.*?)#><br />@s'; $replacement[] = '<div style="background-color:#330000; color:white; padding:10px; font-weight:bold; font-family:GungSuhChe,MonoSpace;">\1</div>'; echo preg_replace($pattern, $replacement, $_POST['code']); exit; ?> 최신 php 는 메모리 관리를 위해 아래와 같은 설정이 포함되었다.
큰 텍스트에 적용할 경우 아무 오류없이 안되어버리는 현상이 있으면, 이 값을 의심하자. pcre.backtrack_limit integer pcre.recursion_limit integer
$spl = preg_split('@(<[^<>]+>|&[a-z\d]+;|\pC|\pM|\pP|\pS|\pZ)+@u', strtolower($utf8_htmlTexts)); 핵심은 \p 입니다. 검색어 인덱싱을 하기 편할겁니다. ▶ 블로그 조회수 베스트 400위 [보기] ▶ 섹시모델 19세 한국계 강이함 사진 [보기] ▶ 50세 이상 비키니 콘테스트 사진 [보기] ▶ SDN48 사진 [보기] ▶ 외제차라면 환장하는 사진 [보기] ▶ 일본 러브텔 사진 [보기] ▶ 예쁜 엉덩이 선발 대회 사진 [보기] ▶ 일산 호수공원의 민폐아줌마 동영상 [보기] ▶ 고속도로에서 배기량빨 믿고 깝치던 체어맨W의 굴욕 동영상 [보기] ▶ 인어시체 발견 [보기] ▶ 민망한 아나운서 비난 [보기] ▶ 중국 버스 수녀 쩍벌녀 동영상 [보기] ▶ 조종사 악명높은 공항 사진 [보기] ▶ 미스 젖은셔츠 선발대회 사진 [보기] ▶ 얼굴이 예뻐지는 기구들 사진 [보기] ▶ 농사짓는 달력 사진 [보기] ▶ 전신스캐너 가리개 사진 [보기] ▶ 훈녀 혼혈 쌍둥이 사진 [보기] ▶ 황홀한 바디페인팅의 세계 사진 [보기] ▶ 병따개 비키니 사진 [보기] ▶ 멕시코 성인식 사진 [보기] ▶ 극한 상황에서 잠자는 사람들 사진 [보기] ▶ 살아있는 외계인 충격 동영상 [보기] ▶ 패리스 힐튼 민망 사진 [보기] ■ 꿈해몽, 꿈풀이 ■ 최신 주소검색, 변경된 우편번호 조회 및 영문우편번호 ■ 웹타자연습, 한글타자(한타), 영문타자(영타), 점수기록 ■ 아이피조회 추적, 국가별 나라별 아이피 국기 ■ 포토샵 없이 웹에서 글자를 이미지로 변환 ■ 만세력 음력양력 변환 달력 (육십갑자,12지,24절기...) ■ 24절기 [二十四節氣] 유래와 세시풍속의 의미 및 뜻 ■ 한눈에 보는 육십갑자표 ■ 디데이 계산 ■ 기념일 계산 ■ 피임진단 : 배란일, 임신기간, 가임주기, 배란기, 생리주기, 임신가능일 계산 프로그램 ■ 구구단 19단표, 19단송 ■ 아라비아숫자 한자변환기(금액 한자변환) ■ 영문오타 한글로 자동변환 ■ 한글 발음을 영어로 변환 ■ 한글 발음을 일어로 변환 ■ 유니코드·헥사코드 변환기
|
||||||||||||||||||||||||||||||||||||||


3,564,299

