我想将文字<b>^FTest</b>
转换为<div class="import">FTest</div>
,这样只有匹配并替换了开始标记时才会匹配和替换结束标记。
更简单的类比:如何轻松切换以下内容:
This is a "simple" test, yes, a "simple" test, that's right a "simple" test.
This is a [simple] test, yes, a [simple] test, that's right a [simple] test.
This is a **simple** test, yes, a **simple** test, that's right a **simple** test.
This is a <b>simple</b> test, yes a <b>simple</b> test, that's right a <b>simple</b> test.
答案 0 :(得分:0)
以下PHP函数应该足够了:
function replacepairs($start, $end, $newstart, $newend, $string) {
$changed = 1;
while ($changed == 1) {
$changed = 0;
$startpos = strpos($string, $start);
if ($startpos !== FALSE) {
$endpos = strpos($string, $end, $startpos + strlen($start));
if ($endpos !== FALSE) {
$stringltstart = 0;
$stringltlength = $startpos - $stringltstart;
$stringlt = substr($string, $stringltstart, $stringltlength);
$stringeqstart = $startpos + strlen($start);
$stringeqlength = $endpos - $stringeqstart;
$stringeq = substr($string, $stringeqstart, $stringeqlength);
$stringgtstart = $endpos + strlen($end);
$stringgtlength = strlen($string) - $stringgtstart;
$stringgt = substr($string, $stringgtstart, $stringgtlength);
$string = $stringlt.$newstart.$stringeq.$newend.$stringgt;
$changed = 1;
}
}
}
return $string;
}
$string = 'This is a "simple" test, yes, a "simple" test, that\'s right a "simple" test.';
echo $string.'<br>'."\n";
$string = replacepairs('"', '"', '[', ']', $string);
echo $string.'<br>'."\n";
$string = replacepairs('[', ']', '**', '**', $string);
echo $string.'<br>'."\n";
$string = replacepairs('**', '**', '<b>', '</b>', $string);
echo $string.'<br>'."\n";