문자열치환문제?

문자열치환문제?

QA

문자열치환문제?

본문

안녕하세요! 문자열 치환하는데 에러가 생겨서요

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

해당 배열은 이거구요 이배열은 하나가 아니라 여러 데이터로 반복 되요

Array   (

   [name] => 홍길동

   [email] => *** 개인정보보호를 위한 이메일주소 노출방지 ***

   [datetime] => 2020년 03월 18일

   [title] => 환영합니다.

   )

 

패턴은 {name} << 이걸 이용해서 안에다가 홍길동 이렇게 변경하려고요

만약에 <div>{name}</div> 이게 있으면 <div>홍길동</div>

 

이런식으로 변경 하고 싶은데 해결 할 방법 좀 알수 있나요?

 

 

이 질문에 댓글 쓰기 :

답변 2

+ preg_replace() : Example #2

- https://www.php.net/manual/en/function.preg-replace.php


$arr = [
   'name' => '홍길동',
   'email' => '*** 개인정보보호를 위한 이메일주소 노출방지 ***',
   'datetime' => '2020년 03월 18일',
   'title' => '환영합니다.',
];
$html = '<div>{name}</div>{title}';
$patterns = [
    '/\{name\}/',
    '/\{title\}/',
];
$replacements = [
    $arr['name'],
    $arr['title'],
];
$html = preg_replace($patterns, $replacements, $html);
echo $html; // <div>홍길동</div>환영합니다.

 

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

 

+ strtr()

- https://www.php.net/manual/en/function.strtr.php


$arr = [
   'name' => '홍길동',
   'email' => '*** 개인정보보호를 위한 이메일주소 노출방지 ***',
   'datetime' => '2020년 03월 18일',
   'title' => '환영합니다.',
];
$html = '<div>{name}</div>{title}';
$html = strtr($html, [
    '{name}'=>$arr['name'],
    '{title}'=>$arr['title'],
]);
echo $html; // <div>홍길동</div>환영합니다.

$name = '홍길동';

echo $name;

 

그리고 array를 잘못 사용하신것 같습니다.

array를 담아줄 변수가 없네요.

$data = array($name, $email, $datetime, $title);

echo $data[0]; // name출력

echo $data[1]; // email출력

echo $data[2]; // datetime출력

echo $data[3]; // title출력

 

제가 질문을 잘 이해한건지 모르겠네요.

잘 해결되시길 바랍니다.

답변을 작성하시기 전에 로그인 해주세요.
전체 59,485
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT