[英]How to replace a Nth occurrence in a string (PHP)
說,有一個數組:
array:4 [
0 => "{__}"
1 => "{one|two|three}"
2 => "{__}"
3 => "{red|green|blue}"
]
和文字:
> Lorem {__} dolor sit amet, consectetur {one|two|three} elit, sed do
> eiusmod tempor incididunt ut labore et dolore {__} aliqua. Ut enim ad
> minim veniam, quis nostrud exercitation ullamco laboris nisi ut
> aliquip ex ea commodo {one|two|three}. Duis {red|green|blue} irure
> dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
> nulla pariatur.
如何將所有{__}替換為<input type="text" name="text[n]" />
(n-條目數),並將所有{a | b | c | ... | N}替換為
<select name="list[n]">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">...</option>
<option value="N">N</option>
</select>
(n-參賽人數)
你的算法應該是這樣的
1-從輸入中讀取字符串
2- $ Step2arr =使用'{__}'中斷數組
3-運行第一步中獲得的數組的foreach
$newstr = '' ;
foreach($Step2arr as $key=>$val){
if( count($Step2arr) - 1 < $key )
$newstr = $newstr.$val.'<input type="text" name="text['.$key.']" /> ' ;
}
4-現在,新字符串具有$ newstr字符串,例如“ Lorem
現在,您也可以對第二個{a | b | c}字符串重復相同的過程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.