簡體   English   中英

PHP在HTML標記中找到某些字符並用字符串替換整個標記

[英]PHP find certain character in HTML tag and replace the whole tag by string

我從我的sql表中提取了一個字符串值,如下所示:

<p>Commodity Exchange on 5 April 2016 settled as following graph:</p> 
<p><img alt=\"\" src=\"ckeditor/plugins/imageuploader/uploads/986dfdea.png\" 
style=\"height:163px; width:650px\" /></p></p> 
<p>end of string</p>

我希望在html標記內獲取圖像名稱986dfdea.png (因為字符串中有很多<p></p>標記,我想知道這個標記包含圖像),並替換整個標記符號內容,如'#image1'。

最終會變成這樣:

<p>Commodity Exchange on 5 April 2016 settled as following graph:</p> 
#image1 
<p>end of string</p>

我正在為移動應用程序開發API,但是擁有PHP的寶貝技能,仍然無法通過引用這些引用來實現我的目標:

PHP / regex:如何獲取HTML標記的字符串值?

如何使用PHP從html中提取img src,title和alt?

請幫忙。

是的,你可以使用正則表達式,你需要更少的代碼,但我們不應該用正則表達式解析html ,所以這就是你需要的:

  1. 您的字符串包含無效的html( </p></p> ),因此我們使用tidy_repair_string來清除它。
  2. 使用DOMXpath()查詢內部帶有img標記的p標記
  3. 刪除任何額外的"並使用getAttribute("src")basename獲取圖像文件basename
  4. 使用image #imagename的值創建一個新的createTextNode
  5. 使用replaceChildp與內部圖像替換為上面創建的新createTextNode
  6. 清理由new DOMDocument();自動生成的!DOCTYPEhtmlbody標簽new DOMDocument();

<?php
$html = <<< EOF
<p>Commodity Exchange on 5 April 2016 settled as following graph:</p>
<p><img alt=\"\" src=\"ckeditor/plugins/imageuploader/uploads/986dfdea.png\"
style=\"height:163px; width:650px\" /></p></p>
<p>end of string</p>
EOF;



$html = tidy_repair_string($html,array(
                           'output-html'   => true,
                           'wrap'           => 80,
                           'show-body-only' => true,
                           'clean' => true,
                           'input-encoding' => 'utf8',
                           'output-encoding' => 'utf8',
                                          ));


$dom = new DOMDocument();
$dom->loadHtml($html);



$x = new DOMXpath($dom);
foreach($x->query('//p/img') as $pImg){
    //get image name
    $imgFileName = basename(str_replace('"', "", $pImg->getAttribute("src")));
    $replace = $dom->createTextNode("#$imgFileName");
    $pImg->parentNode->replaceChild($replace, $pImg);
    # loadHTML causes a !DOCTYPE tag to be added, so remove it:
    $dom->removeChild($dom->firstChild);
    # it also wraps the code in <html><body></body></html>, so remove that:
    $dom->replaceChild($dom->firstChild->firstChild, $dom->firstChild);
    echo str_replace(array("<body>", "</body>"), "", $dom->saveHTML());

}

輸出:

<p>Commodity Exchange on 5 April 2016 settled as following graph:</p>
<p>#986dfdea.png</p>
<p>end of string</p>

Ideone演示

暫無
暫無

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

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