开发者

How to apply formating to a region of text over several divs.

I have the following html.

<div>this is line 1 {start-hidden}</div>
<div>this is line 2</div>
<div>{end-hidden} this is line 3</div>

I want the text between {start-hidden} and {end-hidden} to be not visible. How can I achieve this? Note that the "start-hidden" and "end-hidden" COULD be in different places. It some extra markup.

Do I need some fancy regex or would it be better to use server side DOM manipulation?

Thanks.


The solution I went with (with PHP) (for those interested):

Regex to extract all text (+html) inside the {start-hidden} and {end-hidden} [call this part $inner] as well as all the text before [$pre] and after [$post] it.

preg_match('#^(.*?){start-hidden}(.*?){end-hidden}(.*?)$#is', $source, $matches)

Then remove any cause of new lines within the $inner. Only remove those with closing tags too.

// attempt to remove all sources of new lines
$inner = preg_replace('#<br([^>])*>#is', '', $inner);
$inner = preg_replace('#<div([^>])*>(.*?)</div>#is', '', $inner);
$inner = preg_replace('#<p([^>])*>(.*?)</p>#is', '', $inner);

Then we find every leftover tag and prefix开发者_开发知识库 with </span> and append <span class="hidden">.

$inner = preg_replace('#(<[^>]+>)#is', '</span>${1}<span class="hidden">', $inner),

Then prefix $inner with <span class="hidden"> and append </span>

$inner = '<span class="hidden">' . $inner . '</span>';

Finally join it all back together (and repeat if you can preg_match() again).

$source  = $pre;
$source .= $inner;
$source .= $post;


Do {start-hidden} and {end-hidden} have to be within the and tags as they are? Adhering to html would suggest using something like (it makes no sense to have styles "break" the div as your suggestion does):

<div>this is line 1</div>
<div style="display:none;">this is line 2</div>
<div>this is line 3</div>

or, as was suggested by gred:

<div>this is line 1</div>
<div style="visibility:hidden;">this is line 2</div>
<div>this is line 3</div>

edit: It's important to have a look at the difference between display:none and visibility:hidden:w3schools on display vs. visibility


Use a span:

<div>this is line 1 <span style="visibility:hidden;">{start-hidden}</span></div>
<div>this is line 2</div>
<div><span style="visibility:hidden;">{end-hidden}</span> this is line 3</div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜