首页 > 解决方案 > 从不带 URL 参数的 HTML src 标签中获取 URL

问题描述

我在一个名为例如的变量中有这个内容$iframe

$iframe='<iframe title="Example Iframe" width="640" height="360" src="https://example.com/mypage?parameter=1" frameborder="0" allowfullscreen></iframe>';

而且我需要剥离除 src URL 之外的所有内容,不带参数

在上面的示例中,最终结果应该是这样的:

echo $iframe;

https://example.com/mypage

我不确定是否有一个函数可以在 HTML 字符串中搜索属性,然后可能使用一些正则表达式来去除参数......

标签: phpregex

解决方案


尝试正则表达式

/src=\"(.*?)(\?.*\"|\")/

这里的例子。工作 php 示例在这里

<?php

$re = '/src=\"(.*?)(\?.*\"|\")/';
$str = '\'<iframe title="Example Iframe" width="640" height="360" src="https://example.com/mypage?parameter=1" frameborder="0" allowfullscreen></iframe>\'';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches[0][1]);


推荐阅读