我从数据库中检索了一个 HTML 字符串,需要将所有
s'更改为空格
<p> C G Am</p><p>C G Am F</p>
所以我想将其更改为空格,以便我可以在 pre 元素中使用
<pre></pre>
如下
<pre >
//here i needed to insert the converted string
//for example
C G Am F
C G F C/E Dm C
</pre>
我需要一个解决方案来在 PHP、JS/Jquery 中执行此操作
请帮我解决这个问题
我试过了
$nbsp = html_entity_decode(" ");
$s = html_entity_decode("<p> C G Am</p>");
$s = str_replace($nbsp, " ", $s);
我试过这个,但这将所有 nbsp 替换为一个空格
即使在<pre>
标签内部,HTML 标签也会变成 DOM 元素,浏览器会将多个空格合并为一个。这是此行为的示例。
<pre>
<h1>A heading</h1>
<p>some paragraph</p>
<table>
<tr>
<td>a table</td>
<td>a table</td>
<td>a table</td>
<td>a table</td>
</tr>
</table>
</pre>
此外,为了替换多次出现的搜索字符串,您必须在 的第一个参数中使用正则表达式.replace()
。
解决方案
这使用了一种基本的方法来替换字符串中的 HTML 标记,但这超出了本问题的范围。我添加它是为了能够重现您的案例并能够提供解决方案。
const s = '<p> C G Am</p><p>C G Am F</p>';
let result = s.replace(/(<p>|<br(.*)>)/gi, "\r\n") // replace starting paragraph tags and line break tags with actual line breaks
.replace(/(<\/p>)/gi, "\n") // replace closing paragraph tags with nothing
.replace(/(<(.*)>)/gi, "") // discard any other HTML tags
.replace(/\ /gi, ' '); // replace non-breaking space entities with actual spaces
document.querySelector('#tabs').innerText = result; // insert
<pre id="tabs">
</pre>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句