[PHP]특정문자열 이후의 값만 담기

김이홍·2024년 1월 11일

PHP

목록 보기
11/30
<?php
// 이메일 주소 목록
$emails = ["email1@example.com", "email2@another.com", "email3@different.com"];

// 각 도메인에 대한 메시지
$messages = [
    "example.com" => "Example.com 도메인을 사용하는 사용자에게 보낼 메시지입니다.",
    "another.com" => "Another.com 도메인을 사용하는 사용자에게 보낼 메시지입니다.",
    "different.com" => "Different.com 도메인을 사용하는 사용자에게 보낼 메시지입니다."
];

foreach ($emails as $email) {
    // 이메일 주소에서 도메인 추출
    $domain = substr(strrchr($email, "@"), 1);

    // 도메인에 해당하는 메시지 가져오기
    $message = isset($messages[$domain]) ? $messages[$domain] : "알 수 없는 도메인입니다.";

    // 결과 출력
    echo "이메일 주소: $email - 메시지: $message\n";
}
?>
  1. strrchr($email, "@"):

strrchr 함수는 첫 번째 인자로 주어진 문자열에서 두 번째 인자로 주어진 문자(이 경우 '@' 기호)를 찾아, 그 문자와 그 뒤에 오는 모든 문자들을 반환합니다.
예를 들어, email"someone@example.com"인경우,strrchr(email이 "someone@example.com"인 경우, strrchr(email, "@")는 "@example.com"을 반환합니다.

  1. substr(..., 1):

substr은 ... 문자열에서 INDEX 1번째 부터 반환합니다.
"@example.com"를 입력받으면 "example.com"가 출력됩니다.

0개의 댓글