次の正規表現ルールがあります。
'/((f|ht)tp)(.*?)(.gif|.png|.jpg|.jpeg)/'
それはうまく機能しますが、改行と4つ以上のスペースが前にあるものと一致させたくありません。つまり、次のようなものです。
"\n "
どうすればこれを行うことができますか?
行の先頭に固定された負の先読みを追加しました。改行文字とそれに続く4つ以上の空白文字の存在をチェックします。この条件が存在する場合、一致は失敗します。
'/^(?!\n\s{4,}).*((f|ht)tp)(.*?)(.gif|.png|.jpg|.jpeg)/'
You don't need to include the linefeed itself in the lookahead, just use the start anchor (^
) in multiline mode. Also, since \s
can match all kinds of whitespace including linefeeds and tabs, you're better off using a literal space character:
'/^(?! {4}).*(f|ht)tp(.*?)(.gif|.png|.jpg|.jpeg)/m'
Speaking of tabs, they can be used in place of the four spaces to create code blocks here on SO, so you might want to allow for that as well:
'/^(?! {4}|\t).*(f|ht)tp(.*?)(.gif|.png|.jpg|.jpeg)/m'
Finally, if you want the regex to match (as in consume) only the URL, you can use the match-start-reset operator, \K
. It acts like a positive lookbehind, without the fixed-length limitation:
'/^(?! {4}|\t).*?\K(f|ht)tp(.*?)(.gif|.png|.jpg|.jpeg)/m'