如果文本不包含某个子字符串,则匹配文本



可能的重复项:
正则表达式/预处理:没有匹配项,如果找到

如果字符串中不存在某些内容,我想使用 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=""></a>', $subject);

这个怎么样:

$yourInputString = 'whatever';
$matchPattern = '/^.*?(?<!.png)$/i';
$replacePattern = '$0.png';
$result = preg_replace($matchPattern, $replacePattern, $yourInputString);

请注意,您的输入字符串只需要包含您正在处理的链接,例如:

example.com/image.png

example.com/image

以下是该模式的说明:

# ^.*?(?<!.png)$
# 
# Options: case insensitive
# 
# Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
# Match any single character that is not a line break character «.*?»
#    Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!.png)»
#    Match the character “.” literally «.»
#    Match the characters “png” literally «png»
# Assert position at the end of a line (at the end of the string or before a line break character) «$»

这将是我解决问题的方式,让"非"正则表达式工作是相当棘手的 - 因为它并不是系统的真正设计目的。因此,相反,将逻辑分开,以便您有两个正则表达式...一个搜索类似链接的结构,然后检查要避免的情况:

function replaceWithLink ( $find ) {
  list($link) = $find;
  if ( preg_match('/.(png|gif|image)$/', $link) ) {
    return $link;
  }
  else {
    return '<a href="'.$link.'">'.$link.'</a>';
  }
}
$text = 'This is my test string that contains a url.like/thing but '.
        'it also contains another url.like/thing/that-has-an.image '.
        'should they all be highlighted?';
$expr = '#[a-z0-9:_-.]+/[a-z0-9_-./]+#i';
$func = 'replaceWithLink';
$text = preg_replace_callback($expr, $func, $text);

以上内容比使用一个过于复杂的正则表达式更具可读性,并且易于扩展以处理更多扩展。显然,为了让它与 URL 正常工作,您可能需要调整正在搜索它们的 RegExp - 我只是很快地将一个放在一起。在我的版本中,URL必须包含URL-like text,后跟/,后跟URL-like text possibly with slash才能获得资格。

最新更新