본문 바로가기
PHP

[PHP] preg_match(), preg_match_all(), preg_replace()과 정규식(정규 표현식)

by BeomBe 2023. 11. 17.
반응형

1. preg_match("패턴", 변수)

문자열에서 패턴이 존재하는지 확인

<?php
$str = "Hi User";
$pattern = "/Hi/i";
echo preg_match($pattern, $str); // Outputs 1
?>

 

2. preg_match_all("패턴", 변수)

문자열에서 패턴이 얼마나 존재하는지 확인

<?php
$str = "There are many ingredients in that dish.";
$pattern = "/in/i";
echo preg_match_all($pattern, $str); // Outputs 2
?>

 

3. preg_replace("패턴", "바꾸고싶은 값", 변수)

문자열에서 존재하는 패턴의 값을 변경

<?php
$str = "Visit Seoul!";
$pattern = "/Seoul/i";
echo preg_replace($pattern, "Busan", $str); // Outputs "Visit Busan!"
?>

 

4. 정규식

패턴을 대신하여 정규식을 사용할 수 있다.

public function replaceSpecialChar($_color){
    $_color = preg_replace('/[^A-Za-z0-9\-]/', '-', $_color);
    $_color = str_replace("---", "-", $_color);

    return $_color;
}


public function stringToId($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}


정규 표현식은 아주 많기 때문에 외워서 사용할 순 없고, 경우에 맞게 찾아서 사용하는것이 좋습니다.

아래링크를 타고 들어가서 다양한 정규식 조합을 확인해보시길 추천합니다.

https://www.w3schools.com/php/php_regex.asp

반응형

'PHP' 카테고리의 다른 글

[PHP] Array 배열 정렬 (Array sort)  (1) 2023.11.23
[PHP] isset / unset / empty / is_null / is_numeric  (1) 2023.11.23
[PHP] 문자열 관련함수  (4) 2023.11.22
[PHP] 문자열 합치기  (1) 2023.11.22
[PHP] CURL (Get, Post)  (1) 2023.11.16