使用 HTMLAgility http://htmlagilitypack.codeplex.com/之类的 HTML 解析器可以更轻松地完成此类活动
关于最佳方式的足够的讲座。我想您正在寻找捕获第一个 etword 内部文本并将其拉入替换字段。
我敢肯定这可以在崇高的重写。在 powershell 中,我将通过以下方式完成此操作:
$Matches= @()
$String = '<td class="etword">et alfabet</td>
<td class="etword"> </td>'
# find the value in the preceding cell. if there arn't any matching strings then skip
if ($String -imatch '<td[^>]*class="etword"[^>]*?>([^<]*?)</td>[\s\n]*?<td[^>]*class="etword"[^>]*?> </td>' ) {
$FoundText = $Matches[1]
$WholeMatchingString = $Matches[0]
write-host "Found Text: " $FoundText
write-host "WholeMatchingString: " $WholeMatchingString
# create a new string with the desired values, by replacing with the correct text
$NewString = $WholeMatchingString -replace " ", $('<?php audioButton("../../audio/words/' + $FoundText + '","' + $FoundText + '");?>')
Write-Host "NewString: " $NewString
# replace the whole matcing string with the New string
$String = $String -replace $WholeMatchingString, $NewString
Write-Host "Result: " $String
} # end if
产生以下输出:
Found Text: et alfabet
WholeMatchingString: <td class="etword">et alfabet</td><td class="etword"> </td>
NewString: <td class="etword">et alfabet</td><td class="etword"> </td>
Result: <td class="etword">et alfabet</td><td class="etword"><?php audioButton("../../audio/words/et alfabet","et alfabet");?></td>
在 powershell 中, $Matches 数组会自动填充最后一次匹配操作的结果。