회원가입∴아이디/비번찾기
홈으로


PHP preg match all()
3년 전
정규표현식에 맞는 것을 모두 추출하는 PHP 함수
패턴에 큰따옴표( " ) 사용시 백슬래시가 하나 더 필요하다.

예시 1

모든 태그 추출
preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches);

모든 a 태그 추출
preg_match_all("/(<(a+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches);

모든 맥주소 추출
preg_match_all("/([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}/", $text, $matches);

예시 2: URL 추출

http://, https://로 시작하는 URL 수집
preg_match_all("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $html, $matches);

//, http://, https://로 시작하는 URL 수집
preg_match_all("/(\b(?:(?:https?|ftp):))?\/\/[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $text, $matches);

preg_match_all() 한글단어 추출

$text = "pattern에 주어진 정규 표현식으로 subject에서 모든 매치를 찾아내고,
flags에 지정한 방법에 따라서 matches에 넣습니다.
처음 매치가 발견된 후, 이후 검색은 마지막 매치의 끝에서부터 이루어집니다.";
preg_match_all("|(?<hangul>[가-힣]+)|u", $text, $out);
print_r( $out['hangul'] );

Array
(
[0] => 에
[1] => 주어진
[2] => 정규
[3] => 표현식으로
[4] => 에서
[5] => 모든
[6] => 매치를
[7] => 찾아내고
[8] => 에
[9] => 지정한
[10] => 방법에
[11] => 따라서
[12] => 에
[13] => 넣습니다
[14] => 처음
[15] => 매치가
[16] => 발견된
[17] => 후
[18] => 이후
[19] => 검색은
[20] => 마지막
[21] => 매치의
[22] => 끝에서부터
[23] => 이루어집니다
)

$text = "apple
사과
pear
banana
초코banana
바나나
사과";

preg_match_all("|(?<hangul>[가-힣]+)|su", $text, $out);
print_r( $out['hangul'] );

Array
(
[0] => 사과
[1] => 초코
[2] => 바나나
[3] => 사과
)

preg match all() 영어단어 추출

$str = "Charles Robert Darwin, FRS (12 February 1809 – 19 April 1882) was an English naturalist. He established that all species of life have descended over time from common ancestors, and proposed the scientific theory that this branching pattern of evolution resulted from a process that he called natural selection, in which the struggle for existence has a similar effect to the artificial selection involved in selective breeding.";

preg_match_all('/([a-zA-Z]|\xC3[\x80-\x96\x98-\xB6\xB8-\xBF]|\xC5[\x92\x93\xA0\xA1\xB8\xBD\xBE]){4,}/', $str, $match_arr);
$words = $match_arr[0];
print_r($words);

Array
(
[0] => Charles
[1] => Robert
[2] => Darwin
[3] => February
[4] => April
[5] => English
[6] => naturalist
[7] => established
[8] => that
[9] => species
[10] => life
[11] => have
[12] => descended
[13] => over
[14] => time
[15] => from
[16] => common
[17] => ancestors
[18] => proposed
[19] => scientific
[20] => theory
[21] => that
[22] => this
[23] => branching
[24] => pattern
[25] => evolution
[26] => resulted
[27] => from
[28] => process
[29] => that
[30] => called
[31] => natural
[32] => selection
[33] => which
[34] => struggle
[35] => existence
[36] => similar
[37] => effect
[38] => artificial
[39] => selection
[40] => involved
[41] => selective
[42] => breeding
)

preg match all() 맥주소 추출
예시 1
function extract_mac_address($str) {
preg_match_all("/([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}/", $str, $matches);
return $matches[0];
}
$ifconfig_result = "eth0 Link encap:Ethernet HWaddr 52:54:00:5D:DB:01
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:982 errors:0 dropped:0 overruns:0 frame:0
TX packets:970 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:92188 (90.0 KiB) TX bytes:91468 (89.3 KiB)
eth1 Link encap:Ethernet HWaddr 52:54:00:5D:DB:02
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:982 errors:0 dropped:0 overruns:0 frame:0
TX packets:970 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:92188 (90.0 KiB) TX bytes:91468 (89.3 KiB)";
$mac_addr_arr = extract_mac_address( $ifconfig_result );
print_r( $mac_addr_arr );

Array
(
[0] => 52:54:00:5D:DB:01
[1] => 52:54:00:5D:DB:02
)

예시 2
function extract_mac_address($str) {
preg_match_all("/([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}/", $str, $matches);
return $matches[0];
}
exec("ifconfig", $output);
$ifconfig_result = implode("\n", $output);
$mac_addr_arr = extract_mac_address( $ifconfig_result );
print_r( $mac_addr_arr );
# Array
# (
# [0] => 68:0A:24:79:1C:35
# )

정규표현식 예시

전화번호
^d{3}\-d{4}\-d{4}$
예: 012-3456-7890, 123-4567-8901

^d{2,3}\-d{3,4}\-d{4}$
예: 02-1234-5678, 031-234-5678, 123-456-7890

^01(?:0|1[6-9])\-(?:d{3}|d{4})\-d{4}$

이메일 주소
^[0-9a-zA-Z_\-]+@[.0-9a-zA-Z_\-]+$

^[0-9a-zA-Z_\-]+@[0-9a-zA-Z_-]+(\.[0-9a-zA-Z_\-]+)*$

^[0-9a-zA-Z_\-]+@[0-9a-zA-Z_\-]+(\.[0-9a-zA-Z_\-]+){1,2}$

Java
\\w+@\\w+\\W\\w+

IP 주소
^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$
0.0.0.0 ~ 999.999.999.999

맥 주소
^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$

주민등록번호
^\d{6}\-[1-4]\d{6}$

태그
<textarea … >부터 </textarea>까지
<textarea\b[^>]*>(.*?)</textarea>

한자
[\x4E00-\x9FA5]|[\xF900-\xFA2D]
[\x{4E00}-\x{9FA5}]|[\x{F900}-\x{FA2D}]

다국어
히라가나 [\x{3041}-\x{309e}] / [぀-ゟ]
전각 가타카나 [\x{309b}-\x{309c}\x{30a1}-\x{30fe}] / [゠-ヿ]
반각 가나 [\x{ff61}-\x{ff9f}]
CJK 표의문자 [\x{3400}-\x{9fff}\x{f900}-\x{fa2d}]
힌디어 [\x{0900}-\x{097F}]
러시아어 [\x{0410}-\x{044F}\x{0500}-\x{052F}\x{0400}-\x{04FF}]
모든 한글(자소) 찾기1 [\x{3131}-\x{318E}]|[\x{AC00}-\x{D7A3}]
모든 한글(자소) 찾기2 [\x{1100}-\x{11f9}\x{3131}-\x{318e}\x{ac00}-\x{d7a3}]
태국어 [กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛]
일본 출판사 이름 끝문자 (會|社|書店|書房|書院|堂|大學|文庫|所|館|出版|閣|局|文庫|舍)

교체
HTML 주석 제거
<!--부터 -->까지(줄바꿈 포함)를 빈문자열로 교체
<!--(.|\n|\r)*-->

줄바꿈 2개를 1개로 교체
\n\s*\n
\n








추천추천 : 384 추천 목록
번호 제목
1,320
간단한 게시판 만들기
1,319
PHP에서 MP3 파일을 직접 읽고 스트리밍 하기
1,318
현재 페이지가 location.reload()에 의해 새로고침되었는지
1,317
텍스트 파일을 읽고, 각 줄의 끝에서 6글자를 삭제한 후, 결과를 새로운 파일에 저장합니다.
1,316
cURL을 사용하여 리다이렉트를 따라가 최종 URL 가져오기
1,315
[PHP] $_SERVER 환경변수
1,314
웹서버 ip 확인
1,313
웹호스팅의 절대경로를 확인
1,312
preg match에 관한 정규식
1,311
PHP $ SERVER 환경 변수 정리
1,310
PHP 현재 페이지의 도메인명이나 url등의 정보 알아오기
PHP preg match all()
1,308
PHP 로 웹페이지 긁어오기 모든 방법 총정리!
1,307
[PHP] 원격지 파일 주소 노출 안하고 curl로 다운로드 받기
1,306
PHP 함수 정리
1,305
PHP 배열에서 무작위로 하나 뽑아주는 array rand() 함수
1,304
PHP 정규식 정리
1,303
PHP 정규식을 활용한 태그 및 특정 문자열 제거 및 추출 방법
1,302
php 크롤링 또는 파싱 함수, 정규식 모음
1,301
제이쿼리 기본 명령어
1,300
PHP 파일 존재 여부 파악하기(로컬 파일 존재 및 원격지 파일 존재)
1,299
태그 사이에 있는 텍스트를 추출
1,298
사용자 함수 모음
1,297
마우스,키보드 제한 ( 오른쪽클릭,드래그,영역선택등..)
1,296
PHP - 특정 태그 및 문자열 추출, 제거
1,295
[PHP] define과 defined의 차이
1,294
우클릭 완벽차단 스크립트
1,293
[PHP] dirname()함수와 $_SERVER 관련 상수들
1,292
[PHP] 파일 크기, 사이즈 불러오는 함수, filesize()
1,291
[jQuery] jQuery Quick API
목록
뮤직트로트 부산광역시 부산진구 가야동 ㅣ 개인정보취급방침ㅣ모바일버전
Copyright ⓒ musictrot All rights reserved.