アプリ版:「スタンプのみでお礼する」機能のリリースについて

ラジオボックスのHTMLタグの順序を入れ替え、ラジオボックスごとに<div>タグを付けたいです。

[元のデータ]
$str='<input type="radio" name="data[sample]" id="sample1" value="1" size="" /><label for="sample1">公開</label><input type="radio" name="data[sample]" id="sample2" value="2" size="" /><label for="sample2">非公開</label>';

[出力したいデータ]
<div class="radio">
<label for="sample1">
<input type="radio" name="data[sample]" id="sample1" value="1" size="" />公開
</label>
</div>
<div class="radio">
<label for="sample2">
<input type="radio" name="data[sample]" id="sample2" value="2" size="" />非公開
</label>
</div>

-----------------------------------------------------------------------------------

以前、こちらで(https://oshiete.goo.ne.jp/qa/9133859.html
preg_replaceを使う方法を教えていただきました。


$pattern = '//';
$replacement = '$2$1$3';
$str = preg_replace($pattern, $replacement, $str );


今回は途中にタグを追加する形になっており、その部分がうまくいきません。
ラジオボックス1つごとに<div class="radio"></div>を追加したいです。

ご回答宜しくお願いします。

A 回答 (1件)

こんなかんじですか?



<?PHP
$str='<input type="radio" name="data[sample]" id="sample1" value="1" size="" /><label for="sample1">公開</label><input type="radio" name="data[sample]" id="sample2" value="2" size="" /><label for="sample2">非公開</label>';

$pattern='|(<input type="radio".*?>)(<label .*?>)(.+?)(</label>)|';
$replacement ='<div class="radio">'.PHP_EOL;
$replacement.='$2'.PHP_EOL;
$replacement.='$1$3'.PHP_EOL;
$replacement.='$4'.PHP_EOL;
$replacement.='</div>'.PHP_EOL;
$str=preg_replace($pattern,$replacement,$str);
print $str;
//以下デバッグ用
print nl2br(htmlspecialchars($str));
?>
    • good
    • 0
この回答へのお礼

yambejp様

ご回答ありがとうございます。
求める結果を得ることができました。

自分で $replacementのところに<div class="radio"></div>を加えたり試行錯誤していたのですが、ラジオボックス一つ一つに反映されず先頭と最後に一度だけ<div>が表示されてしまう状態から抜け出せず困っていました。

今後とも宜しくお願いします。

お礼日時:2018/05/08 13:18

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!