2012-07-17 115 views
0

我有一個長字符串,其中包含一個我想要刪除的樣式化標記並用其他字符串替換。 但是我試過了str_replace函數,但它失敗了。任何想法我可以做到這一點?我的代碼在這裏。替換數組中的字符串

$primaryNav = '<li id="menu-item-1178" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1178 sf-ul"> 
       <a href="http://mysite.com/join/" class="sf-with-ul"> 
        <cufon class="cufon cufon-canvas" alt="Get " style="width: 30px; height: 15px; "> 
         <canvas width="45" height="16" style="width: 45px; height: 16px; top: -1px; left: -2px; "></canvas> 
         <cufontext>Get </cufontext> 
        </cufon> 
        <cufon class="cufon cufon-canvas" alt="in" style="width: 15px; height: 15px; "> 
         <canvas width="24" height="16" style="width: 24px; height: 16px; top: -1px; left: -2px; "></canvas> 
         <cufontext>in</cufontext> 
        </cufon> 
        <span class="sf-sub-indicator"><cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; "><canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; "></canvas><cufontext>»</cufontext></cufon></span></a> 
         <ul class="sub-menu" style="visibility: hidden; display: none; "> </ul> 
       </li>'; 

$primaryNav = str_replace('<span class="sf-sub-indicator"><cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; "><canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; "></canvas><cufontext>»</cufontext></cufon></span>', ' It works!', $primaryNav); 
+0

「*我想刪除並替換其他東西。」「那是什麼?你想要取代什麼?請更具體地添加更多描述。 – Lion 2012-07-17 10:23:22

+0

@Lion我想替換一些其他的字符串。 – sammyukavi 2012-07-17 10:24:18

回答

0

您需要考慮標籤之間的空白。這是一個情況下正則表達式可能是一個體面的解決方案:

$primaryNav = preg_replace('#<span class="sf-sub-indicator">\s*<cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; ">\s*<canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; ">\s*</canvas>\s*<cufontext>»</cufontext>\s*</cufon>\s*</span>#', 'It works!', $primaryNav); 

#用於開始/結束的正則表達式,所以你可以忽略它。 \s*表示匹配任意數量的空格,儘可能多次。這將包括空格,製表符,換行符等

請注意,您還可以,使用正則表達式,匹配少了很多,如果你並不需要儘可能多的細節:

$primaryNav = preg_replace('#<span class="sf-sub-indicator">.*?</span>#', 'It works!', $primaryNav); 

注意,這最後一個將停止匹配第一個</span>,所以如果你有多個,你需要小心 - 正則表達式不支持這種'平衡'。

+0

@ Jay ..你的回答不起作用。 – sammyukavi 2012-07-17 10:30:59

+0

你在嘗試哪一個?我已經測試了兩個,他們的工作。你可以嘗試第二個嗎? – Jay 2012-07-17 22:44:59