Apply wordwrap to html content, excluding html attributes

好久不见. 提交于 2020-01-05 07:08:40

问题


I'm not used to regular expressions so this might seem easy while tricky for me.

Basically, i'm applying wordwrap to content, that contains classic html tags : , ...

  $text = wordwrap($text, $cutLength, " ", $wordCut);
  $text = nl2br(bbcode_parser($text));
  return $text;

As you can see, my problem is pretty simple : all I want is to apply wordwrap() to my content, excluding what could be in html attributes : href , src ...

Could someone help me out ? Thanks a lot !


回答1:


You shouldn't use regex for html parsing of course, but this should separate out
content should you want to. I have limited knowledge of php so this just illustrates procedure.

$tags = 
'  <
   (?:
       /?\w+\s*/?
     | \w+\s+ (?:".*?"|\'.*?\'|[^>]*?)+\s*/?
     | !(?:DOCTYPE.*?|--.*?--)
   )>
';

$scripts =
'   <
   (?:
       (?:script|style) \s*
     | (?:script|style) \s+ (?:".*?"|\'.*?\'|[^>]*?)+\s*
   )>
   .*?
   </(?:script|style)\s*>
';

$regex = / ($scripts | $tags) | ((?:(?!$tags).)+) /xsg;

The replacement string is Group1 catted to the return value of your word wrap function (which is passed the content, Group2 string) so something like: replacement = \1 . textwrap( \2 )
Inside of textwrap you decide what to do with the content.

Tested in Perl (btw its very slow and watered down for clarity):

use strict;
use warnings;

my $tags = 
'  <
   (?:
       /?\w+\s*/?
     | \w+\s+ (?:".*?"|\'.*?\'|[^>]*?)+\s*/?
     | !(?:DOCTYPE.*?|--.*?--)
   )>
';

my $scripts =
'   <
   (?:
       (?:script|style) \s*
     | (?:script|style) \s+ (?:".*?"|\'.*?\'|[^>]*?)+\s*
   )>
   .*?
   </(?:script|style)\s*>
';

my $html = join '', <DATA>;

while ( $html =~ / ($scripts | $tags) | ((?:(?!$tags).)+) /xsg ) {
    if (defined $2 && $2 !~ /^\s+$/) {
        print $2,"\n";
    }
}



回答2:


Use any DOM parser capable of extracting the text nodes from the document. Iterate over the text nodes, apply wordwrap on them and write them back to their respective text nodes.

The approach is identical to that one given in

  • How to replace text URLs and exclude URLs in HTML tags?

just instead of checking the text content for links, you apply your wordwrap on them.

The more general phrasing of your problem would be: "How to (selectively) fetch the text content of a HTML document to apply a function to it"



来源:https://stackoverflow.com/questions/4682878/apply-wordwrap-to-html-content-excluding-html-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!