簡體   English   中英

使用REGEX(PHP代碼)替換兩個HTML標記之間的所有“ foo”

[英]replace all “foo” between two HTML tags using REGEX (PHP code)

我想要一個正則表達式代碼,以在html標簽pre> </ pre>之間將所有“ foo”字符串替換為“ bar”

這是一個例子:

< html>
< p> blah blah blah foo try foo< /p>
< pre> foo try foo word foofoo < /pre>
< /html>

應該

< html>
< p> blah blah blah foo try foo< /p>
< pre> bar try bar word barbar < /pre>
< /html>

因此,這意味着標記pre之間的所有foo應該替換為。

我試圖使用此正則表達式模式,但無法正常工作。

do {
$string = preg_replace('/< pre>([^)]*)foo([^)]*< /pre>)/U', '\1boo\2', $string, -1,$count);
}while($count != 0);
echo $string;

我的英語不好意思,謝謝

$string = '< html>
< p> blah blah blah foo try foo< /p>
< pre> foo try foo word foofoo < /pre>
< /html>';
$string = preg_replace('/foo(?=(?:.(?!< pre>))*< \/pre>)/Um', 'boo', $string);
echo $string;

您可以使用DOMDocument提取HTML標記的文本內容,對文本執行簡單的str_replace並更新DOM。

首先,獲取簡單HTML Dom

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find the first pre (you can change this or find an array based on documentation on website to suit your needs, but I will make it just for the first pre for now
$html->find('pre', 0)->plaintext = str_replace('foo', 'bar', $html->find('pre', 0)->plaintext);

//Echo HTML
echo $html;

暫無
暫無

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

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