생활코딩공부/PHP

PHP 함수의 사용

루체도 2019. 9. 5. 14:14

함수라는 것은 PHP에서 제공해주는 함수를 사용을 할 수도 있지만

자신이 함수를 직접 만들어서 사용을 할 수도 있습니다.

직접 만들기 전에 이미 편의성을 위해 만들어진 함수에 익숙해진 다음

자신만의 함수를 만드는 것이 도움이 더 많이 됩니다.

그래서 PHP에서 함수를 사용을 해보도록 하겠습니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h1>Function</h1>
    <?php
    $str ="Lorem ipsum dolor sit amet consectetur adipisicing elit. 
    Itaque architecto eos deserunt laborum repellendus maxime natus, 
    dolore, consectetur reprehenderit, tempora voluptates libero non ab incidunt. 
    Incidunt, earum? Iusto, voluptate? Unde?";
    echo $str;
    ?>
    <h2>strlen()</h2>
    <?php
    echo strlen($str);
    ?>
</body>
</html>

strlen라는 함수를 사용해서 위에 $str 변수의 글자 수를 세어봤습니다. 

$str의 문자열에서 줄바꿈을 하고 싶다면 어떻게 해야할까요? 줄바꿈을 하고 싶은 부분에 가서 <br>태그를 html같이 작성을 해주시면 됩니다. 그런데 이 방법말고도 다른 방법이 있습니다.

검색을 한번 해보도록 합시다. PHP new line to br

http://docs.php.net/manual/kr/function.nl2br.php

 

PHP: nl2br - Manual

This is example with "\R" regex token which matches any unicode newline character."u" flag treate strings as UTF-16. Which is optional, depending on your use case. ', $string);}?>NOTE:preg_replace versions are much slower than using str_replace version or

docs.php.net

뒤에 boolean 변수는 추가적인 제어를 통해서 더 많은 것을 할 수 있다는 뜻인데 우선 이부분은 무시하고 진행을 하도록 하겠습니다. 이제 이것을 통해 php에서 줄바꿈을 해보도록 하겠습니다.

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h1>Function</h1>
    <?php
    $str ="Lorem ipsum dolor sit amet consectetur adipisicing elit. 
    Itaque architecto eos deserunt laborum repellendus maxime natus, 


    dolore, consectetur reprehenderit, tempora voluptates libero non ab incidunt. 
    Incidunt, earum? Iusto, voluptate? Unde?";
    echo $str;
    ?>
    <h2>strlen()</h2>
    <?php
    echo strlen($str);
    ?>
    <h2>nl2br()</h2>
    <?php 
    echo nl2br($str);
    ?>
</body>
</html>

위 사진을 보면 n12br을 통해서 <br>로 바뀐 것을 확인할 수 있습니다. 작성을 하고 검사를 통해 코드를 확인하면

제대로 확인을 할 수 있습니다.