2013-05-30 14 views
0

比如我有一個img標籤這樣的...在保存到數據庫之前,用特定的類替換所有的img標籤?

<img alt="INLINE:143246;w=240;h=240" class="wysiwyg-inline-image" src="/sites/default/files/styles/inline_image_temp_240x240/public/2013/05/30/600x600_30.png?itok=7mP9F2QH" /> 

我希望它由...

<p><!-- INLINE:143220;w=240;h=240 --></p> 

保存到數據庫基於img alt屬性之前替換。

注意:圖片的數量是動態的,因此用戶可能會上傳多張不同尺寸的圖片。圖像尺寸在圖像上。

到目前爲止,我有這樣的代碼。

preg_match_all("/(<img[^>]+>)/i", $node->body[LANGUAGE_NONE][0]['value'], $matches); 

foreach($matches as $match) { 
    // Replace all matched elements here. 
} 

回答

3

如果要替換它,請使用preg_replace。考慮你得到了$ str變量中的字符串,接下來將使用preg_replace來完成它。

$str = preg_replace('/<img.*?alt="(.+?)".*?>/', '<p><!-- $1 --></p>', $str);

+0

哪裏的了'$ 1'來自?它是否將'$ str'視爲數組,並且alt處於位置1? – ninjascorner

+0

$ 1將包含模式的第一個匹配的字符串。是的,在這種情況下它將包含alt值。 – Jithin

+0

你不需要'preg_match_all'並做循環,你只需要用'preg_replace'替換代碼 – Jithin

3
$html = $node->body[LANGUAGE_NONE][0]['value']; // saving value in a variable to manipulate 
preg_match_all("/(<img[^>]+>)/i", $html , $matches); // returns all image tags 

foreach($matches as $match) { 
    $str = preg_replace('/<img.*alt="(.+?)".*?>/', '<p><!-- $1 --></p>', $html); 
    // get the alt tag text 
    $html = str_replace($mathch, $str, $html); replace in the original string 
} 
// save $html in database 
+0

我不認爲你必須一次使用preg_replace和str_replace。等等..,你從我的答案中複製了preg_replace行,因此你的代碼將輸出一個未定義的$ str變量警告,因爲它在preg_replace行之前沒有使用。更好地將其更改爲$ html :-P – Jithin

+0

謝謝,是的,它是錯誤的,@Jithin –

+0

這一個作品,如果我只有一個圖像,但不是如果超過1。 – ninjascorner

相關問題