Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - Regex match images but not inside img tag

I have a function which converts all external image links into img tags in a string. It works well but also matches links inside <img> tag

for example:

$text = '<p>lorem ipsum http://example.jpg <img src="example.jpg"></p>';
echo make_clickable($text);

function make_clickable($text) {
    $replace = '<p class="update-image"><a href="$0" target="_blank"><img src="$0"></a></p>';
    $text = preg_replace('~https?://[^/s]+/S+.(jpg|png|gif)~i', $replace, $text );
    return $text;
}

this test will match both, plain text and src too. it there a way to exclude img tag?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may use some non-well-known regex power:

<img[^>]*>(*SKIP)(*FAIL)|https?://[^/s]+/S+.(?:jpg|png|gif)

Let's explain the pattern a bit:

<img                # match a literal <img
[^>]*               # match anything except > zero or more times
>                   # match a literal >
(*SKIP)(*FAIL)      # make it fail
|                   # or
https?              # match http or https
://                 # match a literal ://
[^/s]+             # match anything except white-space and forward slash one or more times
/                   # match a literal /
S+                 # match a non-white-space one or more times
.                  # match a literal dot
(?:jpe?g|png|gif)   # match jpg, jpeg, png, gif
                    # Don't forget to set the i modifier :)

The idea is to match the img tag and skip it, meanwhile match all those URI's.

Online demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...