Skip to content
Advertisement

Change iframe src with regex

I’m trying to change the src attribute of an iframe from http to https. For example, my string is:

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

What I need is to change it to

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

By far, I’ve been trying with preg_replace but no results:

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

Thank you

Advertisement

Answer

Try the following REGEX instead(DEMO):

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

But beware, You CAN NOT parse HTML with REGEX properly. Please, use some XML parser instead.

Also, it seems you only want to change http to https. So for that try the following instead:

if(strpos($string, 'https') === false)
{
    $string = str_replace("http", "https", $string);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement