簡體   English   中英

匹配除給定字符串外的所有內容

[英]Match everything except given string

好的,這是我嘗試的2個小時。 現在是時候在stackoverflow上問別人了。

我有這個源HTML:

<div class="post_main">
Post Content (has HTML)
</div><div class="post_email">[...]
Other Stuff
<div class="post_main">
Post Content (has HTML)
</div><div class="post_email">[...]
Other Stuff
<div class="post_main">
Post Content (has HTML)
</div><div class="post_email">[...]

等等。 我想在每個帖子內容之前添加“內容”。

為此,我使用了preg_replace,但是它不起作用。 因為我實際上正在使用

'|<div class="post_main">(.*)</div><div class="post_email">|s

作為正則表達式,

"</div><div class="post_email">"

從(。*)中被吃掉,我只有一個替代而不是3。

現在,我如何獲得這個預浸料比賽:

匹配所有包含換行符的內容,但排除給定的字符串(在這種情況下:

"</div><div class="post_email">")

非常感謝。

function addSomething($str,$add) {
  $find = '/(<div class=\"post_main\">)/';
  $replace = '$1' . $add;
  return preg_replace($find, $replace, $str);
}

Mitabell的回答非常適合您的情況。 如果您仍然想按照自己的方式做-只需添加一個小“?” 在“ *”號之后。 我的意思是這樣的:

'|<div class="post_main">(.*?)</div><div class="post_email">|s

它調用了懶惰的數量詞 ,使您的正則表達式變得更少貪婪。

暫無
暫無

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

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