简体   繁体   English

JavaScript 正则表达式替换 HTML 锚点

[英]JavaScript regular expression to replace HTML anchors

I got a HTML string and from this I want to convert some special a tags to something else.我得到了一个 HTML 字符串,我想从这个字符串中将一些特殊的 a 标签转换为别的东西。 I need this for a TinyMCE plugin.我需要这个 TinyMCE 插件。 I tried to change Wordpress wpgallery plugin.我试图改变 Wordpress wpgallery 插件。

For example: These are in HTML string例如:这些在 HTML 字符串中

<a href="http://www.yahoo.com">Yahoo</a> 
<a href="http://www.google.com">Google</a>
<a href="#" rel='special' title='link cat_id="4" content_id="5" content_slug="Slug 1"'>Some where else</a>

Here I have to find special link one and convert it to something else from it's title value like:在这里,我必须找到一个特殊的链接并将其从它的标题值转换为其他内容,例如:

{link cat_id="4" content_id="5" content_slug="Slug 1"}

i need return value like this to insert it into MySQL我需要这样的返回值将其插入 MySQL

<a href="http://www.yahoo.com">Yahoo</a> 
<a href="http://www.google.com">Google</a>
{link cat_id="4" content_id="5" content_slug="Slug 1"}

I tried this我试过这个

function getAttr(s, n) {
            n = new RegExp(n + '="([^"]+)"', 'g').exec(s);
            return n ? tinymce.DOM.decode(n[1]) : '';
        };

return co.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function(a,im) {
var cls = getAttr(im, 'rel');
   if ( cls.indexOf('special') != -1 )
       return '{'+tinymce.trim(getAttr(im, 'title'))+'}';

   return a;
});

this这个

/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g

does not find tags with rel eq to 'special' but all the others.没有找到带有rel eq 到“特殊”的标签,但没有找到所有其他标签。

You might want to look into the DOMDocument and related classes.您可能想查看 DOMDocument 和相关类。 They are much better at parsing HTML than a homebrewed regex solution would be.他们在解析 HTML 方面比自制的正则表达式解决方案要好得多。

You can create a DOMdocument using your supplied markup, execute getElementsByTagName to get all the hyperlinks, scan their attributes for a rel attribute with the value of special, and then take the appropriate action.您可以使用提供的标记创建 DOM 文档,执行 getElementsByTagName 以获取所有超链接,扫描它们的属性以查找值为 special 的 rel 属性,然后采取适当的操作。

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

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