开发者

Match all code between two HTML tags using REGEX

开发者 https://www.devze.com 2023-01-13 20:12 出处:网络
I\'m looking for a greedy RegEx match to replace all text in a number of HTML files between </title> and </head> (I\'ve combined loads of JavaScript files to minimize the number of http re

I'm looking for a greedy RegEx match to replace all text in a number of HTML files between </title> and </head> (I've combined loads of JavaScript files to minimize the number of http requests).

I've googled it but the majority of the solutions don't seem to work for me. (Which naturally leads me to assume that i'm wrong)

This is my current expression which doesn't seem to work:-

</title>([^<]*)</head>

I'm using Dreamweaver 8 search and replace.

Between the two tags there are multiple includes for various javascript files for example:- which vary on a page by page basis.

I want to replace ev开发者_StackOverflow社区erything between those two tags in all pages with a consistant list of CSS / JavaScript inclues.


If DreamWeaver regex supports look-ahead assertions:

</title>((?:(?!</head>)[\s\S])*)</head>

The usual warning "don't work on HTML with regex, this will fail at some point" applies. The points where this would fail could be:

<script>var str = "something that contains </head>";<script>

or

<!-- a comment that refers to </head> -->

among other constellations.


Have you tried using something like http://www.regextester.com/ ? You could test your regex live?

There are other approaches you could take to 'test' your case.


//if i consider you are using php as you are looking for regex
//regex : '#\<\title\>(.+?)\<\/head\>#s'
//in php

    $content_processed = preg_replace_callback(
      '#\<\title\>(.+?)\<\/head\>#s',
      create_function(
        '$matches',
        'return htmlentities($matches[1]);'
      ),
      $content
    );

// this will return content between the tag
0

精彩评论

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

关注公众号