2011-04-14 49 views
0

使用緩存插件修復無數熱鏈接後,一些生成的html保存到數據庫中並不完全正確。例如:修復鏈接href和img src在大量html數據庫中保存在WordPress數據庫中不匹配

<a href="http://www.mbird.com/wp-content/uploads/2011/04/psycho_blanket.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 164px; height: 251px;" src="http://www.mbird.com/wp-content/uploads/2011/04/psycho_blanket1.jpg" alt="" id="BLOGGER_PHOTO_ID_5306768463834252178" border="0"></a> 

其他時間在擴展前還有一個額外的2。其他時間有一個21.

正如你所看到的,href和src不同意。 href是正確的。

如何解決的建議?我猜我需要對post_content中的鏈接圖像做一個正則表達式來測試這個?我沒有太多的正則表達式在PHP中的經驗,並需要一些幫助。

$posts = get_posts(); 

foreach($posts as $post) { 

    // retrieve content of post; same as $post->post_content 
    $content = $post['post_content']; 

    // do stuff that I'm unsure about with $content to hone in on linked images with mismatched filenames and fix them 

    // write it back 
    $post['post_content'] = '$content; 

    // Update the post into the database 
    wp_update_post($my_post); 
} 

回答

1

該測試的正則表達式溶液應該這樣做:

$re = '% # Match IMG wrapped in A element. 
(<a\b[^>]+?href=")([^"]*)("[^>]*><img\b[^>]+?src=")([^"]*)("[^>]*></a>) 
%ix'; 
$content = preg_replace($re, '$1$2$3$2$5', $content); 

鑑於IMG元素包裹的A元素中,該代碼替換爲A元素的HREF屬性IMG元素的SRC屬性。它假定所有的HREF和SRC屬性值都用雙引號括起來。

+1

不錯。讓我爲該主題提供我最喜歡的鏈接:[是否有像開源世界中的RegexBuddy?](http://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-開放源代碼世界)讓OP檢查並學習這個正則表達式的工作原理。 – mario 2011-04-14 04:13:31

+0

我應該提到每個'$ post ['post_content']'中的鏈接圖像上方和下方都有相當多的text/html,並且這個問題可能會在'post'中出現好幾次。 @馬里奧感謝,很好的資源!不再有任何理由從我的PHP正則表達式問題。 – 2011-04-14 12:26:04

+1

@ two7s_clash:這個'preg_replace()'調用將會掃描一個包含多個鏈接圖像實例的大文本,並且將把它們全部修復爲一次。 – ridgerunner 2011-04-14 15:41:52

0

這很容易用正則表達式實現。不過,我想偷懶這裏訴諸phpQuery或QueryPath(它似乎是一個一次性的操作,這樣你就不會需要注意的性能):

$html = qp($content); 

foreach ($html->find("a img") as $img) { 

    $img->attr("src", 
      $img->parent()->attr("href") 
    ); // or maybe add some if checks here 
} 

$post["post_content"] = $html->top("body")->writeHTML(); 

未經測試。您可能還需要一個比"a img"更具體的選擇器。