用正则表达式更改iframe src

时间:2017-11-01 14:22:08

标签: php regex

我正在尝试将iframe的src属性从http更改为https。例如,我的字符串是:

<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>

我需要的是将其改为

<p>Some random text <iframe src="https://some-random-link.com" width="425" height="350" frameborder="0" ></iframe></p>

到目前为止,我一直在尝试使用preg_replace但没有结果:

$res = preg_replace( '/<iframe\s+.*?\s+src="http(.*?)".*?<\/iframe>/', '<iframe\s+.*?\s+src="https$1".</iframe>', $string);

谢谢

3 个答案:

答案 0 :(得分:2)

你可以试试这个正则表达式:

/(<iframe.+?src=".*?)(?=:)/

现场演示here

php中的示例代码:

$re = '/(<iframe.+?src=".*?)(?=:)/';
$str = '<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>';
$subst = '\\1s';

$result = preg_replace($re, $subst, $str);

echo $result; 
// <p>Some random text <iframe src="https://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>

答案 1 :(得分:1)

尝试使用以下REGEX(DEMO):

/<iframe.*?s*src="http(.*?)".*?<\/iframe>/

但要注意,您无法正确解析使用REGEX的HTML。请改用一些XML解析器。

此外,您似乎只想将http更改为https。因此,请尝试以下方法:

if(strpos($string, 'https') === false)
{
    $string = str_replace("http", "https", $string);
}

答案 2 :(得分:-1)

为什么要使用合法的DOM解析器而不是regex-即使对于这样小的字符串操作也如此?

  • 因为正则表达式不是“可识别DOM的”-它将不是标签的子字符串视为是标签,只是因为它类似于标签。

  • 因为无论您是否同意,您的输入可能会略有变化。

  • 因为随着应用程序的成熟,所需的字符串操作可能会变得越来越复杂。

  • 因为使用专用工具来完成他们要解决的任务,所以您似乎是一个仔细,考虑周全且专业的IT工匠。

首先,仅使用DOM解析器和URL解析器的iframe节点循环,然后使用substr_replace()注入's',而不会删除任何原始字符。

代码:(Demo

$html = <<<HTML
<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ($dom->getElementsByTagName('iframe') as $iframe) {
    $src = $iframe->getAttribute('src');
    if (parse_url($src, PHP_URL_SCHEME) === 'http') {
        $iframe->setAttribute('src', substr_replace($src, 's', 4, 0));
    }
}
echo $dom->saveHTML();

或者,您可以使用XPath定位合格的src属性。

代码:(Demo

$html = <<<HTML
<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe>
<iframe src="https://cant-touch-this.com" width="425" height="350" frameborder="0"></iframe>
</p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//iframe[starts-with(@src, 'http') and not(starts-with(@src, 'https'))]/@src") as $src) {
    $src->nodeValue = substr_replace($src->nodeValue, 's', 4, 0);
}
echo $dom->saveHTML();

这些技术不仅比regex更加可靠,而且这些解析器的语法更容易被人类阅读,并且随着时间的推移将使您的脚本更易于管理。