简体   繁体   English

去掉 <ul> 字符串开头和结尾的标签(JavaScript或PHP)

[英]Remove <ul> tags from beginning and end of string (JavaScript or PHP)

I receive data in the following format from the server 我从服务器接收以下格式的数据

<ul>
    <li>Some text</li>
    <li>Other text</li>
</ul>

Basically string containing a standard unordered list. 基本上是包含标准无序列表的字符串。 What I want to do now is to remove the ul tags that wrap the list items, so that I would only receive the inner content. 我现在想做的是删除包裹列表项的ul标签,这样我将只接收内部内容。 Like this: 像这样:

<li>Some text</li>
<li>Other text</li>

It might be worth mentioning that ul tags will always be present when I get the data so I don't realy care whats inside it, or are there any more ul tags nested within. 可能值得一提的是,当我获取数据时ul标签将始终存在,因此我并不真正在意其中的内容,或者是否还有嵌套的ul标签。 I just need to remove the outer ones and get the data inside. 我只需要删除外部的数据并获取内部的数据。

Either a JavaScript or PHP solution would be welcomed. 欢迎使用JavaScript或PHP解决方案。

var div = document.createElement("div");
div.innerHTML = "<ul><li></li></ul>";
div.firstChild.innerHTML; //"<li></li>"

Note that .firstChild will only be ul if there is no whitespace/text at the beginning of the string. 请注意,仅当字符串开头没有空格/文本时, .firstChild才会为ul

In that case you could use: 在这种情况下,您可以使用:

var div = document.createElement("div");
div.innerHTML = "    <ul><li></li></ul>";
div.getElementsByTagName("ul")[0].innerHTML //"<li></li>"

instead 代替

var txt="<ul>\n    <li>Some text</li>\n    <li>Other text</li>\n</ul>";
var result=txt.replace(/^<ul>\s*/,'').replace(/\s*<\/ul>$/,'');
text.replace(/^<ul>/, "")​​​​​​​​​​​​.replace(/<\/ul>$/, "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM