[PHP/WEB] 정규표현식으로 여러개의 <br>태그를 하나 또는 두개로 줄이는 방법 질문합니다.

조회수 1182회

현재 간단한 리얼타임 대나무숲 게시판을 개발중에 있습니다.

index.php에서 post로 보낸 데이터를 multi.php에서 처리하여 DB에 저장한 다음, 다시 index.php에서 보여주는 예제입니다.

index.php 일부

index.php에서는 shift+enter로 줄바꿈을 할 수 있는 textarea(설정은 index.js에서...)와 hidden input인 cmd(이 값은 include/multi.php에서 처리합니다.), 그리고 submit button이 있습니다.

<form class="ui form" method="post" action="./include/multi.php" id="bamboo">
    <div class="ui fluid action input">
        <textarea name="contents" type="text" placeholder="어떤 말을 전하고 싶나요? 줄바꿈은 SHIFT + ENTER!" required form="bamboo" id="textarea"></textarea>
        <input type="hidden" name="cmd" value="3">
        <button type="submit" name="submit" class="ui submit button">올리기</button>
    </div>
</form>

include/multi.php 일부

multi.php에서는 post된 cmd의 value에 따라 switch 문으로 여러개의 케이스를 처리합니다. 이때 줄바꿈이 연속으로 입력될 경우 줄바꿈이 너무 많다는 알림을 출력합니다.

include("dbconfig.php");
define("CMD_REQUEST_UPLOAD", 3);

switch ((int) $_POST['cmd']) {
    case CMD_REQUEST_UPLOAD:
        if (isset($_POST["submit"])) {
            if (empty($_POST["contents"])) {
                die("<script>alert('empty'); history.go(-1);</script>");
            } else if (strlen($_POST["contents"]) > 4000) {
                die("<script>alert('입력하신 내용이 너무 길어요!'); history.go(-1); </script>");
            } else if (strlen($_POST["contents"]) < 30) {
                die("<script>alert('입력하신 내용이 너무 짧아요!'); history.go(-1); </script>");
            } else if (strpos($_POST["contents"], "<br><br><br>")!==false){
                die("<script>alert('줄바꿈이 너무 많네요ㅜㅜ'); history.go(-1); </script>");
            } else if(preg_match('/(?:\s*<br[^>]*>\s*){4,}/s', $_POST["contents"])) {
                die("<script>alert('줄바꿈이 너무 많네요ㅜㅜ'); history.go(-1); </script>");
            } else {
                $contents = $_POST['contents'];
                $contents = preg_replace('/(?:\s*<br[^>]*>\s*){3,}/s', '<br><br>', $contents);
                $contents = htmlspecialchars($contents);
                $contents = addslashes($contents);
                $contents = stripslashes($contents);
                $contents = mysqli_real_escape_string($conn, $contents);

                $ip = $_SERVER['REMOTE_ADDR'];

                $sql = "insert into bamboo(contents, ip) 
                    values('$contents','$ip')";
                $mysqli->query($sql);
                die("<script>alert('성공적으로 입력되었습니다!'); history.go(-1);</script>");
            }
        }
        break;

index.js 일부

index.js는 엔터키와 shift키가 동시에 눌렸을때 <br>태그로 바꿉니다.

$(document)
    .ready(function () {
        $("#textarea").keypress(function (e) {
            if(e.which == 13 && !e.shiftKey) { 
                $('#contents').val().replace(/\n/g, "<br>")   
                e.preventDefault();
                return false;
            }
        });
    });

여기에서 질문은 아래와 같습니다.

  1. 정규표현식으로 4개 이상의 <br>태그 연속(<br><br><br><br>...)을 preg_match로 확인한 다음 die하려 합니다.
  2. 정규표현식으로 3개의 <br>태그 연속(<br><br><br>...)을 preg_replace로 <br> 2개로 바꾸려 합니다.

정규표현식을 쓰긴 했는데 재대로 입력이 되지 않고 있습니다. (여러개의 줄바꿈이 그대로 DB에 저장됩니다ㅠㅠ)도와주시면 감사하겠습니다!

  • (•́ ✖ •̀)
    알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)