채택완료

explode관련 질문입니다.

2020-11-14 (토) 01:00:43 2,521

<?php
$str = "Hello, world,  beautiful, day";
print_r (explode(" ,",$str));
?>

위와 같이 할 때,
Hello
world
beautiful
 day
이렇게 되잖아요?
 그런데

$str = "Hello(P), world(P),  beautiful(Q), day(Q)";
print_r (explode(" ,",$str));
?>
위와 같이 해서
P-Hello, world
Q-beautiful,day
이렇게 할 수 있는 방법좀 없을까요?

고수님들 방법이 있으면 좀 알려주실수 있나요?
감사합니다.
넙죽

|

답변 1개

채택된 답변
+20 포인트

참조하세요.

$str = "Hello(P), world(P),  beautiful(Q), day(Q)";
$pattern = "#(\w+)(\(\w\)),\s+(\w+)(\(\w\)),\s+(\w+)(\(\w\)),\s+(\w+)(\(\w\))#";
$replace = "$2-$1, $3 || $6-$5, $7";

$str2 = preg_replace($pattern, $replace, $str);
$str2 = str_replace(array("(",")"),"",$str2);
$arr = explode("||", $str2);

print_r($arr);

답변을 작성하려면 로그인이 필요합니다.