开发者

JavaScript regular expression to replace HTML anchors

开发者 https://www.devze.com 2023-03-19 01:13 出处:网络
I got a HTML string and from this I want to convert some special a tags to something else. I need this for a TinyMCE plugin. I tried to change Wordpress wpgallery plugin.

I got a HTML string and from this I want to convert some special a tags to something else. I need this for a TinyMCE plugin. I tried to change Wordpress wpgallery plugin.

For example: These are in HTML string

<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

<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.


You might want to look into the DOMDocument and related classes. They are much better at parsing HTML than a homebrewed regex solution would be.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消