扩展PHP正则表达式以涵盖“srcset”和“style”属性

时间:2017-02-28 作者:Ethan O\'Sullivan

我创建了一个插件,可以将所有链接转换为protocol-relative URLs (正在删除http:https:) 基于我在$tag$attribute 变量。这是功能的一部分。为了节省空间,the rest of the code can be found here.

$tag = \'a|base|div|form|iframe|img|link|meta|script|svg\';
$attribute = \'action|content|data-project-file|href|src|srcset|style\';
# If \'Protocol Relative URL\' option is checked, only apply change to internal links
if ( $this->option == 1 ) {
    # Remove protocol from home URL
    $website = preg_replace( \'/https?:\\/\\//\', \'\', home_url() );
    # Remove protocol from internal links
    $links = preg_replace( \'/(<(\' . $tag . \')([^>]*)(\' . $attribute . \')=["\\\'])https?:\\/\\/\' . $website . \'/i\', \'$1//\' . $website, $links );
}
# Else, remove protocols from all links
else {
    $links = preg_replace( \'/(<(\' . $tag . \')([^>]*)(\' . $attribute . \')=["\\\'])https?:\\/\\//i\', \'$1//\', $links );
}
这是预期的结果,但在以下示例中不起作用:

<!-- Within the \'style\' attribute -->
<div class="some-class" style=\'background-color:rgba(255,255,255,0);background-image:url("http://placehold.it/300x200");background-position:center center;background-repeat:no-repeat\'>
<!-- Within the \'srcset\' attribute -->
<img src="http://placehold.it/600x300" srcset="http://placehold.it/500 500x, http://placehold.it/100 100w">
然而,该代码部分适用于这些示例。

<div class="some-class" style=\'background-color:rgba(255,255,255,0);background-image:url("http://placehold.it/300x200");background-position:center center;background-repeat:no-repeat\'>
<img src="http://placehold.it/600x300" srcset="//placehold.it/500 500x, http://placehold.it/100 100w">
我一直在尝试为$tag$attribute 变量,但这没有帮助。我假设我需要更新剩余的正则表达式来覆盖这两个额外的标记?或者是否有不同的方法,例如DOMDocument?

1 个回复
最合适的回答,由SO网友:Ethan O\'Sullivan 整理而成

我能够使用下面的正则表达式覆盖所有标记&;协议属性:

/<(?:input\\b[^<]*\\bvalue=[\\"\\\']https?:\\/\\/|link\\b[^<]*?\\brel=[\\\'\\"]canonical[\\\'\\"][^<]*?>)(*SKIP)(*F)|https?:\\/\\//
这是更新的部分:

# If \'Relative\' option is selected, remove domain from all internal links
$exceptions = \'<(?:input\\b[^<]*\\bvalue=[\\"\\\']https?:\\/\\/|link\\b[^<]*?\\brel=[\\\'\\"]canonical[\\\'\\"][^<]*?>)(*SKIP)(*F)\';
if ( $this->option == 2 ) {
    $website = preg_replace( \'/https?:\\/\\//\', \'\', home_url() );
    $links = preg_replace( \'/\' . $exceptions . \'|https?:\\/\\/\' . $website . \'/\', \'\', $links );
}
# For all external links, remove protocols
$links = preg_replace( \'/<(?:input\\b[^<]*\\bvalue=[\\"\\\']https?:\\/\\/|link\\b[^<]*?\\brel=[\\\'\\"]canonical[\\\'\\"][^<]*?>)(*SKIP)(*F)|https?:\\/\\//\', \'//\', $links );

相关推荐

无法在模板函数.php中使用IS_HOME

我试图在标题中加载一个滑块,但只在主页上加载。如果有帮助的话,我正在使用Ultralight模板。我正在尝试(在template functions.php中)执行以下操作:<?php if ( is_page( \'home\' ) ) : ?> dynamic_sidebar( \'Homepage Widget\' ); <?php endif; ?> 但这行不通。现在,通过快速的google,我似乎需要将请