문자열치환문제?
본문
안녕하세요! 문자열 치환하는데 에러가 생겨서요
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출력
제가 질문을 잘 이해한건지 모르겠네요.
잘 해결되시길 바랍니다.