정규표현식에 맞는 것을 모두 추출하는 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] => 이루어집니다
)
$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.";