簡體   English   中英

PHP / regex-用絕對(相對於href存在)查找(並替換)相對URL

[英]PHP/regex - Find (and replace) relative url with absolute (regardless of href existence)

我正在開發一個小型PHP項目,需要用絕對版本替換字符串中找到的每個相對url。 問題是,我已經找到了很多關於這個問題的答案,但所有這些都需要在URL前面加上href。 我需要轉換的簡單示例如下:

<link rel="alternate" type="application/atom+xml" title="Feed for question &#39;preg_replace to change url from relative to absolute&#39;" href="/feeds/question/19373024">
        <meta name="twitter:app:country" content="US" />
        <meta name="twitter:app:name:iphone" content="Stack Exchange iOS" />
        <meta name="twitter:app:id:iphone" content="871299723" />
        <meta name="twitter:app:url:iphone" content="se-zaphod://stackoverflow.com/questions/19373024/preg-replace-to-change-url-from-relative-to-absolute" />

在這種情況下,它應顯示為(轉換后)為:

<link rel="alternate" type="application/atom+xml" title="Feed for question &#39;preg_replace to change url from relative to absolute&#39;" href="http://stackoverflow.com/feeds/question/19373024">
        <meta name="twitter:app:country" content="US" />
        <meta name="twitter:app:name:iphone" content="Stack Exchange iOS" />
        <meta name="twitter:app:id:iphone" content="871299723" />
        <meta name="twitter:app:url:iphone" content="se-zaphod://stackoverflow.com/questions/19373024/preg-replace-to-change-url-from-relative-to-absolute" />
$pattern = '/\"\/feeds\/question/';
$subject = "href='/feeds/question/19373024'>";
$replacement = "http://stackoverflow.com/feeds/question";
echo preg_replace($pattern, $replacement, $subject);

編輯:您可以在preg_replace中使用$ pattern設置正則表達式模式。 我在這里做了這個: https : //regex101.com/r/xB0dY5/1

然后在$ subject中,我加載了一個帶有“提要/問題”的字符串。 在$ replacement中,應該替換正則表達式所選內容的字符串。

您應該使用“(quote)(” / feeds ...)來進行正則表達式,否則它還會選擇第二個鏈接的feeds / questions。

暫無
暫無

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

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