我创建了一个插件,可以将所有链接转换为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?
最合适的回答,由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 );