You can use the below script to remove all empty p/P tags (having space
or
).
This script uses the HtmlDecode
method of System.Web.HttpUtility
class to decode single or multiple occurrences of
to an empty string and then Regex replaces p tags with or without spaces.
$items = Get-ChildItem "master:/sitecore/content" -Recurse -Language *
foreach($item in $items){
Write-Host "Item - " $item.Paths.Path
foreach($field in $item.Fields){
if($field.Type -eq "Rich Text"){
$rawValue = $field.Value
if($rawValue -like '*<p*'){
$output = [System.Web.HttpUtility]::HtmlDecode($rawValue)
$output = $output -replace "(<(P|p)>)\s*(<\/(P|p)>)",'' #To remove <p></p> or <p> {HAVING SPACES IN BETWEEN} </p> or <P></P> or <P> {HAVING SPACES IN BETWEEN} </P>
$output = $output -replace "(<(P|p)\s*\/>)",'' #To remove self closed p tags e.g. <p/> or <p />
$item.Editing.BeginEdit()
$item.Fields[$field.Name].Value = $output
$item.Editing.EndEdit()
Write-Host "Field - " $field.Name
Write-Host ""
}
}
}
}
Tested with
<p>p tag with text</p><p/><p /><p></p><div>hello</div><p> </p>
Output
<p>p tag with text</p><div>hello</div>