PHP & Others

php 정규표현식

페이지 정보

본문

정규표현식 문법

정규식결과
fooThe string “foo”
^foo“foo” at the start of a string
foo$“foo” at the end of a string
^foo$“foo” when it is alone on a string
[abc]a, b, or c
[a-z]Any lowercase letter
[^A-Z]Any character that is not a uppercase letter
(gif|jpg)Matches either “gif” or “jpeg”
[a-z]+One or more lowercase letters
[0-9.-]Ðny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$Any word of at least one letter, number or _
([wx])([yz])wy, wz, xy, or xz
[^A-Za-z0-9]Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})Matches three letters or four numbers

정규표현식을 사용하는 함수 

FunctionDescription
preg_match()문자열에 지정한 패턴이 존재하면 true, 아니면 false를 리턴
preg_match_all()지정한 패턴과 일치하는 모든 문자열을 배열에 저장
preg_replace()지정한 패턴과 일치하는 문자열을 교체
preg_split()패턴을 기준으로 문자열을 분리하려 배열로 리턴
preg_grep()배열중에 지정된 패턴을 포함하는 요소들을 배열로 리턴
preg_ quote()지정된 패턴 앞에 ''(역슬래쉬)를 추가한 문자열을 리턴.

자주 사용되는 함수들

 

// 도메인 유효성 검증

 

$url = "http://www.naver.com/";

if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {

    echo "Your url is ok.";

} else {

    echo "Wrong url.";

}

 

 

// 특정 문자의 강조

 

$text = preg_replace("/b(강조할문자)b/i", '<span style="background:#5fc9f6">1</span>', $text);

echo $text;

 

// 검색어에 효과주기

 

$title  = get_the_title();

$keys= explode(" ",$s);

$title  = preg_replace('/('.implode('|', $keys) .')/iu',

'<strong class="search-excerpt">\0</strong>', $title);

 

// 문서에 삽입된 모든 이미지 추출

 

$images = array();

preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media);

unset($data);

$data=preg_replace('/(img|src)("|'|="|=')(.*)/i',"$3",$media[0]);

foreach($data as $url)

{

$info = pathinfo($url);

if (isset($info['extension']))

{

if (($info['extension'] == 'jpg') ||

($info['extension'] == 'jpeg') ||

($info['extension'] == 'gif') ||

($info['extension'] == 'png'))

array_push($images, $url);

}

}

 

// 반복 입력된 단어 제거

$text = preg_replace("/s(w+s)1/i", "$1", $text);

 

// 반복 입력된 부호 제거

$text = preg_replace("/.+/i", ".", $text);

 

// XML/HTML 태그 추출

 

function get_tag( $tag, $xml ) {

  $tag = preg_quote($tag);

  preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>.'}',

                   $xml,

                   $matches,

                   PREG_PATTERN_ORDER);

 

  return $matches[1];

}

 

// 특정 속성을 포함하는 XML/HTML 태그 추출

 

function get_tag( $attr, $value, $xml, $tag=null ) {

  if( is_null($tag) )

    $tag = '\w+';

  else

    $tag = preg_quote($tag);

 

  $attr = preg_quote($attr);

  $value = preg_quote($value);

 

  $tag_regex = "/<(".$tag.")[^>]*$attr\s*=\s*".

                "(['\"])$value\\2[^>]*>(.*?)<\/\\1>/"

 

  preg_match_all($tag_regex,

                 $xml,

                 $matches,

                 PREG_PATTERN_ORDER);

 

  return $matches[3];

}

 

// 16진수 컬러값 체크

 

$string = "#555555";

if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) {

echo "example 6 successful.";

}

 

 

// 웹페이지의 타이틀 추출

 

$fp = fopen("http://www.catswhocode.com/blog","r");

while (!feof($fp) ){

    $page .= fgets($fp, 4096);

}

$titre = eregi("<title>(.*)</title>",$page,$regs);

echo $regs[1];

fclose($fp);

 

// 아파치 로그 파싱

 

//Logs: Apache web server

//Successful hits to HTML files only.  Useful for counting the number of page views.

'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?.html?)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)200s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'

 

//Logs: Apache web server

//404 errors only

'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)404s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'

 

// 겹따옴표를 홑따옴표로 교체

preg_replace('B"b([^"x84x93x94rn]+)b"B', '?1?', $text);

 

 

// 비밀번호 완성도 체크

//Tests if the input consists of 6 or more letters, digits, underscores and hyphens.

//The input must contain at least one upper case letter, one lower case letter and one digit.

'\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}\z'

 

// WordPress 이미지 표시

 

<?php if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

 

<?php

$szPostContent = $post->post_content;

$szSearchPattern = '~<img [^>]* />~';

 

// Run preg_match_all to grab all the images and save the results in $aPics

preg_match_all( $szSearchPattern, $szPostContent, $aPics );

 

// Check to see if we have at least 1 image

$iNumberOfPics = count($aPics[0]);

 

if ( $iNumberOfPics > 0 ) {

     // Now here you would do whatever you need to do with the images

     // For this example the images are just displayed

     for ( $i=0; $i < $iNumberOfPics ; $i++ ) {

          echo $aPics[0][$i];

     };

};

 

endwhile;

endif;

?>

 

// 특정 이모티콘을 이미지로 교체

 

$texte='A text with a smiley :-)';

echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);

[출처] php 정규표현식|작성자 칼리보

 

 

 

 

 

관련자료

등록된 댓글이 없습니다.
Today's proverb
행복해지고 싶다면, 잠시 동안만이라도 가슴에 손을 얹고 생각해 보라. 그러면 진정한 즐거움은, 발치에 돋아나는 잡초나 아침 햇살에 빛나는 꽃의 이술과 같이 우리 주변에 무수히 널려 있다는 것을 알 수 있을 것이다. 《하루 5분 생각이 인생을 결정한다 》 (이범준)