개발하는 루루언니

php : preg_match / preg_replace 문자열 매칭/ 치환 본문

php

php : preg_match / preg_replace 문자열 매칭/ 치환

혜닝혜루 2023. 5. 31. 15:01
728x90
반응형

★  preg_match 

<?php 
$text = ' Hello World! Tom '
$reg = preg_match('/\btom\b/i' , $text, $matches);

?>
  • tom 이라는 문자열을 대소문자 관계없이 매칭한 값을 취득하는 정규식 표현이다.

 

★결과

array(1) { [0]=> string(3) "Tom"}

 

 

★ preg_match_all

preg_match 은 매칭되는 값을 찾게 되면 그 시점에서 검색이 종료 된다.

하지만 매칭되는 모든 값을 취득하고 싶은 경우에는 적합하지 않기 때문에 매칭되는

모든 값을  취득하고 싶을 때에는 preg_match_all 함수를 사용한다.

<?php
$text = 'My name is Tom, I heard You are also tom , right? No, I am Tommy'
$reg = preg_match_all('/\btom\b/i' , $text, $matches );
?>​

 

★ 결과

array(1) { [0]=> array(2) { [0]=> string(3) "Tom" [1]=> string(3) "Tom" } }

검색 결과에는 Tom과 tom 이 매칭되어 2개의 값을 배열로 취득하였다.

참고로 Tommy 는 매칭되지 않는다 ( \b 으로 지정했기 때문이다)

 

★preg_replace 

🌈 숫자만 추출

$str = 'test_@$1234';
$str = preg_replace("/[^0-9]*/s", "", $str);

결과 : 1234 

  • test_@$1234  숫자만 추출하게되면 특수문자가 제거된 값이 추출되게 된다. 

🌈 특수문자 제거 (-,_ 제외)

$str = 'test_@$1234';
$str = preg_replace("/[ #\&\+%@=\/\\\:;,\.'\"\^`~\!\?\*$#<>()\[\]\{\}]/i", "", $str);

결과 = test_1234

 


🌈 스크립트 제거 

$str = 'hello <script>alert(\'hi\')</script>';
$str = preg_replace("/<script>.*<\/script>/s", "", $str);
// hello
728x90