我有一个字符串($options)
存储在PHP变量中,其中包含一系列<option>
元素,如下所示:
<option class="level-0" value="898">Text 1</option>
<option class="level-1" value="33"> Text 2</option>
<option class="level-2" value="543"> Text 3</option>
<option class="level-1" value="547"> Text 4</option>
<option class="level-0" value="3328">Text 5</option>
我想将每个value
的内容替换为一个函数的结果,该函数采用前一个值来生成URL。URL字符串(它是可变的)应该成为每个相应<option>
的新值。
我不确定这是否可以实现preg_replace
,但我会知道如何做到这一点,如果每个选项是一个数组与键,但它是一个可变字符串…你会怎么做?
$lines = explode(PHP_EOL, $options);
$new_options = array();
foreach ($lines as $option_line) {
//do the preg replace for each line (quick and dirty regexp)
$replaced_string_value = preg_replace('/>('w+)<'//i', '>replacement<''', $option_line);
//add it to the new array
$new_options[] = $replaced_string_value;
}
$options = implode(PHP_EOL, $new_options);