简体   繁体   中英

How to replace a Nth occurrence in a string (PHP)

Say, there is an array:

array:4 [
  0 => "{__}"
  1 => "{one|two|three}"
  2 => "{__}"
  3 => "{red|green|blue}"
]

and text:

> 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.

How to replace all {__} to <input type="text" name="text[n]" /> (n - number of entry) and all {a|b|c|...|N} to

<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 - number of entry)

Your Algo should be something like

1- read string from input

2- $Step2arr = break to arrays using '{__}'

3- run foreach for array that we got from step one

$newstr = '' ;

foreach($Step2arr as $key=>$val){
    if( count($Step2arr) - 1 < $key )
    $newstr  = $newstr.$val.'<input type="text" name="text['.$key.']" /> ' ; 
}

4- Now new string have something $newstr string like "Lorem

Now you could repeat the same process for second {a|b|c} string also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM