簡體   English   中英

php regex獲取href標記內的字符串

[英]php regex to get string inside href tag

我需要一個正則表達式,可以在href標簽和引號內為我提供字符串。

例如,我需要在以下位置提取theurltoget.com:

<a href="theurltoget.com">URL</a>

另外,我只想要基本網址部分。 即來自http://www.mydomain.com/page.html我只希望http://www.mydomain.com/

不要為此使用正則表達式。 您可以使用xpath和內置的php函數來獲取所需的內容:

    $xml = simplexml_load_string($myHtml);
    $list = $xml->xpath("//@href");

    $preparedUrls = array();
    foreach($list as $item) {
        $item = parse_url($item);
        $preparedUrls[] = $item['scheme'] . '://' .  $item['host'] . '/';
    }
    print_r($preparedUrls);
$html = '<a href="http://www.mydomain.com/page.html">URL</a>';

$url = preg_match('/<a href="(.+)">/', $html, $match);

$info = parse_url($match[1]);

echo $info['scheme'].'://'.$info['host']; // http://www.mydomain.com

此表達式將處理3個選項:

  1. 無引號
  2. 雙引號
  3. 單引號

'/ href = [“ \\']?([^^ \\'>] +)[” \\']?/'

如果您只在尋找基本網址部分 (@David問題的第二部分),請使用@Alec的答案!

$html = '<a href="http://www.mydomain.com/page.html" class="myclass" rel="myrel">URL</a>';
$url = preg_match('/<a href="(.+)">/', $html, $match);
$info = parse_url($match[1]);

這將為您提供:

$info
Array
(
    [scheme] => http
    [host] => www.mydomain.com
    [path] => /page.html" class="myclass" rel="myrel
)

因此,您可以使用$href = $info["scheme"] . "://" . $info["host"] $href = $info["scheme"] . "://" . $info["host"] $href = $info["scheme"] . "://" . $info["host"]可為您提供:

// http://www.mydomain.com  

當您在href之間查找整個URL時 ,您應該使用另一個正則表達式,例如@ user2520237提供的正則表達式。

$html = '<a href="http://www.mydomain.com/page.html" class="myclass" rel="myrel">URL</a>';
$url = preg_match('/href=["\']?([^"\'>]+)["\']?/', $html, $match);
$info = parse_url($match[1]);

這將為您提供:

$info
Array
(
    [scheme] => http
    [host] => www.mydomain.com
    [path] => /page.html
)

現在,您可以使用$href = $info["scheme"] . "://" . $info["host"] . $info["path"]; $href = $info["scheme"] . "://" . $info["host"] . $info["path"]; 這給你:

// http://www.mydomain.com/page.html

http://www.the-art-of-web.com/php/parse-links/

讓我們從最簡單的情況開始-格式正確的鏈接,沒有額外的屬性:

/<a href=\"([^\"]*)\">(.*)<\/a>/iU

對於所有href值替換:

function replaceHref($html, $replaceStr)
{
    $match = array();
    $url   = preg_match_all('/<a [^>]*href="(.+)"/', $html, $match);

    if(count($match))
    {
        for($j=0; $j<count($match); $j++)
        {
            $html = str_replace($match[1][$j], $replaceStr.urlencode($match[1][$j]), $html);
        }
    }
    return $html;
}
$replaceStr  = "http://affilate.domain.com?cam=1&url=";
$replaceHtml = replaceHref($html, $replaceStr);

echo $replaceHtml;

這將處理URL周圍沒有引號的情況。

/<a [^>]*href="?([^">]+)"?>/

但是請注意, 不要使用regex解析HTML 使用DOM或適當的解析庫。

因為正向和負向落后很酷

/(?<=href=\").+(?=\")/

它只會匹配您想要的內容,不帶引號

數組([0] => theurltoget.com)

/href="(https?://[^/]*)/

我認為您應該能夠處理其余的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM