可能的重复项:
正则表达式/预处理:没有匹配项,如果找到
如果字符串中不存在某些内容,我想使用 preg_replace
来替换一些字符串。也就是说,如果子字符串存在,则字符串将不匹配。
例如,如果字符串包含 .png
,则不会找到/匹配它。
example.com/image.png
在这里,它找不到它,因为字符串包含行/子字符串.png
。
example.com/image
在这里,它会找到它,因为字符串不包含.png
任何地方的行/子字符串。
对于那些仍然没有得到我的人。
$result = preg_replace("#http://(.*S)[Something here that will not match the link if it finds the .png at last]#","<a href='\1'>\1</a>","Here is a link that should work http://example.com/; Here is a link that should NOT work http://example.com/image.png")
好吧,我要在这里四处走动。
首先,您需要一个正则表达式,该正则表达式将为您找到一个URL。由于您显然也想找到许多无效的URL,因此我们将采用一个正则表达式,该正则表达式仅考虑包含序列<letter>.<letter>
的任何连续非空格字符字符串:
b(?=S*[a-z].[a-z])S+(?=s|$)
然后我们可以检查这个序列是否以 .png
结尾:
b(?=S*[a-z].[a-z])S+(?=s|$)(?<!.png)
现在您可以将其用于替换操作,例如
$result = preg_replace(
'/b # Start at a word boundary
(?= # Assert that it's possible to match...
S* # any number of non-whitespace characters
[a-z].[a-z] # followed by an ASCII letter, a dot, a letter
) # End of lookahead assertion
S+ # Match one or more non-whitespace characters
(?=s|$) # until the next whitespace or end of string
(?<!.png) # unless that match ends in .png/ix',
'<a href=" ">