2012-07-24 55 views
0

我知道這看起來很簡單,但我很難完成這項任務。如何搜索給定字符串內的HTML標籤?

我需要從一個數組的鍵/值刪除所有HTML的img標籤,然後把這些去掉HTML IMG標籤,這個時候把它們放回到同一個陣列,它有自己單獨的數組鍵。

樣品:

$array = array(
    'content' => '<img src="http://www.domain.com/images/img.png" width="100" height="100" alt="" />here is some content that might also be in this string.' 
); 

$array = array(
    'content' => 'here is some content that might also be in this string.', 
    'image' => '<img src="http://www.domain.com/images/img.png" width="100" height="100" alt="" />' 
); 

的HTML IMG標記和字符串內文本的其餘部分將永遠是不同的。內容永遠不會完全一樣,所以我不知道如何去做這件事。我正在考慮explode()str_replace()

+1

也許你可以看看DOM文檔,HTML解析器http://php.net/manual/en/class.domdocument.php – ajreal 2012-07-24 15:45:57

回答

1

你需要一個正則表達式。喜歡的東西:

$pattern = '#<img(.*)/>#U'; // note need to use ungreedy match here.'; 
$number_of_matches = preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE); 

這會告訴你匹配的數量,對比賽的信息(包括匹配的字符串和匹配字符串,您將使用從原始字符串中移除內容的偏移量)