从 img src 中删除 http:


Remove http: from img src

使用 php 是否可以从 img src 中删除 http: 协议?

所以img src将是:

<img src="//www.example.com/image.jpg" />

而不是

<img src="http://www.example.com/image.jpg" />

str_replace在这里会是一个不错的选择吗?我知道我可以定义:

$contentImg = str_replace(array('http', 'https'), '', $filter);

我只是不确定如何定义$filter。

是的str_replace is where it's at . 它将是一个协议相对链接。

<?php echo str_replace(array('http:', 'https:'), '', 'http://www.google.com'); ?>

它输出

//www.google.com

这符合预期。 否则,您可以使用允许您使用正则表达式或正则表达式的preg_replaceCommuSoft发布了一个很好的例子。

假设$filter工作正常并且源代码被正确获取,您还可以使用正则表达式替换:

$contentImg = preg_replace('/^https?:/','', $string);

'/^https?:/'这里是正则表达式: - ^字符表示字符串的开头,因此您只需删除前面的潜在协议。 - ?是一个特殊字符,用于指定s是可选的。因此,它将匹配http:https:

使用正则表达式,您可以编写一些更紧凑的查询。说(为了回答)你也希望删除ftpsftp,你可以使用:

'/^(https?|s?ftp):/'

由于|表示和括号用于分组目的。

您还忘记删除冒号(:)。

但是,我更担心您的$filter将包含整个页面源代码。在这种情况下,它可能弊大于利,因为包含http:的文本也可以被删除。为了解析和处理XML/HTML,最好使用DOMParser。这将带来一些开销,但正如一些软件工程师所争辩的那样:"软件工程是针对傻瓜的工程系统,宇宙目前产生越来越多的傻瓜,因此一点点额外的开销是合理的"。

例:

你绝对应该使用 DOMParser,如前所述(因为这种方法更故障安全):

$dom = new DOMDocument;
$dom->loadHTML($html); //$html is the input of the document
foreach ($dom->getElementsByTagName('img') as $image) {
    $image->setAttribute('src',preg_replace('/^https?:/','',$image->getAttribute('src')));
}
$html = $dom->saveHTML(); //html no stores the new version

(在php -a中运行此操作会为您提供测试示例的预期输出)。

或者在后处理步骤中:

$html = get_the_content();
$dom = new DOMDocument;
$dom->loadHTML($html); //$html is the input of the document
foreach ($dom->getElementsByTagName('img') as $image) {
    $image->setAttribute('src',preg_replace('/^https?:/','',$image->getAttribute('src')));
}
$html = $dom->saveHTML();
echo $html;

性能:

使用php -a交互式 shell(1'000'000 个实例)对性能进行了测试:

$ php -a
php > $timea=microtime(true); for($i = 0; $i < 10000000; $i++) { str_replace(array('http:', 'https:'), '', 'http://www.google.com'); }; echo (microtime(true)-$timea);  echo "'n";
5.4192590713501
php > $timea=microtime(true); for($i = 0; $i < 10000000; $i++) { preg_replace('/^https?:/','', 'http://www.google.com'); }; echo (microtime(true)-$timea);  echo "'n";
5.986407995224
php > $timea=microtime(true); for($i = 0; $i < 10000000; $i++) { preg_replace('/https?:/','', 'http://www.google.com'); }; echo (microtime(true)-$timea);  echo "'n";
5.8694758415222
php > $timea=microtime(true); for($i = 0; $i < 10000000; $i++) { preg_replace('/(https?|s?ftp):/','', 'http://www.google.com'); }; echo (microtime(true)-$timea);  echo "'n";
6.0902049541473
php > $timea=microtime(true); for($i = 0; $i < 10000000; $i++) { str_replace(array('http:', 'https:','sftp:','ftp:'), '', 'http://www.google.com'); }; echo (microtime(true)-$timea);  echo "'n";
7.2881300449371

因此:

str_replace:           5.4193 s     0.0000054193 s/call
preg_replace (with ^): 5.9864 s     0.0000059864 s/call
preg_replace (no ^):   5.8695 s     0.0000058695 s/call

对于更多可能的零件(包括sftpftp):

str_replace:           7.2881 s     0.0000072881 s/call
preg_replace (no ^):   6.0902 s     0.0000060902 s/call