簡體   English   中英

需要PHP Regex幫助

[英]PHP Regex help needed

我在PHP中有一個像下面這樣的變量。

$content = 'abc def <img src="https://www.example.com/images/abc.png" /> end';

我必須使用正則表達式刪除img src之外的所有內容。 所以最終值:

$content = 'https://www.example.com/images/abc.png';

我在Java中使用正則表達式來執行此操作,但是我必須在PHP中執行該操作,但我無法執行。

Java代碼:

Pattern p = Pattern.compile("<img[^>]*src=[\\\"']([^\\\"^']*)");
Matcher m = p.matcher(content);
while (m.find()) {
    String src = m.group();
    int startIndex = src.indexOf("src=") + 5;
    content = src.substring(startIndex, src.length());
    break; // break after first image is found
}

我是PHP的新手,正在這里掙扎。

如果可以選擇,請避免使用正則表達式來解析HTML數據。 在這種情況下,HTML解析器更安全:

$dom = new domDocument;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($content);

$imgs = $dom->getElementsByTagName('img');
$srcs = array();

for ($i = 0; $i < $imgs->length; ++$i) {
    $srcs[] = $imgs->item($i)->getAttribute('src');
}

如果確定只有一個img標簽,則可以執行以下操作:

// ...
$content = $dom->getElementsByTagName('img')->item(0)->getAttribute('src');

在PHP中完全相同。 我用regex101.com生成了代碼

$re = '/<img[^>]*src=[\\\\\"\']([^\\\\\"^\']*)/';
$str = 'abc def <img src="https://www.example.com/images/abc.png" /> end';

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

// Print the entire match result
var_dump($matches);

快到了。 如果只需要第一個圖像(如代碼所示),則可以使用preg_match()

<?php
$re = '/<img[^>]*src=[\\\"\']([^\\\"^\']*)/i';
$str = 'abc def <img src="https://www.example.com/images/abc.png" /> end';
preg_match($re, $str, $matches);
echo $matches[1];

演示

暫無
暫無

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

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