• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

preg_replace_callback 질문드립니다.

22.07.16 16:11 작성 조회수 214

0

var_dump(preg_replace_callback('/^(.*)@(.*)$/',
    function($matches){
    return $matches;
}, 'hmmi@kakao.com'));

 

이렇게 했을 때 오류가 나타나는 이유가 뭘까요??

 

답변 1

답변을 작성해보세요.

1

이 코드를 보면 경고를 던집니다. 배열을 문자열로 변환할 수 없다고 말이죠. preg_replace_callback() 의 두번째 파라매터에 들어가는 콜백은 반환 값이 배열이 아닌 문자열이어야 합니다.

PHP: preg_replace_callback - Manual

callback

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This is the callback signature:

handler(array $matches): string


$matches
는 배열이죠. 따라서 다음과 같이 수정할 수 있습니다.

$str = preg_replace_callback(
    '/^(.*)@(.*)$/',
    function ($matches) {
        [$email, $user, $domain] = $matches;

        return $email;
    }, 
    'hmmi@kakao.com'
);

var_dump($str);