假设$filter 工作正常并且源被正确获取,您也可以使用正则表达式替换:
$contentImg = preg_replace('/^https?:/','', $string);
'/^https?:/' 这里是一个正则表达式:
- ^ 字符表示字符串的开头,这样您只删除前面的潜在协议。
- ? 是一个特殊字符,指定s 是可选的。因此它将匹配http: 和https:。
使用正则表达式,您可以编写一些更紧凑的查询。说(为了回答)你也想删除ftp和sftp,你可以使用:
'/^(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
更多可能的部分(包括sftp和ftp):
str_replace: 7.2881 s 0.0000072881 s/call
preg_replace (no ^): 6.0902 s 0.0000060902 s/call