我需要一个正则表达式(PHP)来获取一个完整的URL,其中包含一个包含多个URL的文本块中的某个字符串。
E.g。
正则表达式在以下文本中搜索包含特殊关键字的网址。
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>
<a href="http://example.org/specialkeyword/test/testing">url</a>
<a href="http://example.org/notkeyword/test/testing">url</a>
<p>
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
<script>
var Url = 'http://example.org/notkeyword/test/testing';
var Url2 = 'https://example.org/specialkeyword/test/testing';
</script>
如果有帮助,网址将始终包含在单引号或双引号中。
答案 0 :(得分:2)
如果有帮助,网址将始终包含在单引号或双引号中。
如果您绝对需要使用正则表达式,可以考虑以下内容:
preg_match_all('~(?=[\'"]https?.*specialkeyword)[\'"]\K[^\'"]*~', $text, $matches);
print_r($matches[0]);
<强>解释强>:
(?= # look ahead to see if there is:
[\'"] # any character of: '\'', '"'
http # 'http'
s? # 's' (optional)
.* # any character except \n (0 or more times)
specialkeyword # 'specialkeyword'
) # end of look-ahead
[\'"] # any character of: '\'', '"'
\K # '\K' (resets the starting point of the reported match)
[^\'"]* # any character except: '\'', '"' (0 or more times)