正则表达式用于提取某些URL?

时间:2011-07-07 08:35:13

标签: php regex

我已经尽了最大努力,但正则表达式并不是我的事。 :(

我需要提取某些以特定文件扩展名结尾的网址。例如,我希望能够解析一个大段落并提取所有以*.txt结尾的网址。例如,

  

Lorem ipsum dolor坐下来,精神上的精神。 Nulla hendrerit aliquet erat at ultrices。 Donec eu nunc nec nibh http://www.somesite.com/somefolder/blahblah/etc/something.txt iaculis dictum。 Quisque nisi neque,vulputate quis pellentesque blandit,faucibus eget nisl。

我需要能够从上一段中取出 http://www.somesite.com/somefolder/blahblah/etc/something.txt ,但要提取的网址数量会有所不同。它将根据用户输入的内容而动态变化。它可以有3个以*.txt结尾的链接和3个不以*.txt结尾的链接。我只需要提取那些以*.txt结尾的内容。任何人都可以为我提供我需要的代码吗?

3 个答案:

答案 0 :(得分:1)

您可以使用/(?<=\s)http:\/\/\S+\.txt(?=\s)/

找到所需内容

这意味着:

  • 之前的空格/制表符/新行。
  • 的http://
  • 多一个非空格字符。
  • .txt的
  • 之后的空格/制表符/换行符。

答案 1 :(得分:0)

假设这些都是正确的URL,那么它们就不会有任何空格。我们可以利用这个事实使正则表达式变得非常简单:

preg_match_all("/([^ ]+\.(txt|doc))/i", $text, $matches);
//   ([^ ]+     Match anything, except for a space.
//   \.         A normal period.
//   (txt|doc)  The word "txt" or "doc".
//   )/i        Case insensitive (so TXT and TxT also work)

如果您不需要匹配多个文件扩展名,则可以将“(txt | doc)”更改为“txt”。

$matches将包含许多数组,您需要键号0或1.为了使数组更易于阅读,您可以使用:

preg_match_all("/(?P<matched_urls>[^ ]+\.(txt|doc))/i", $text, $matches);

这会使$matches看起来像这样:

array([0] => array(), [1] => array(), [2] => array(), ["matched_urls"] => array());

应该明白你需要哪个键。

答案 2 :(得分:0)

怎么样:

$str = 'Lorem ipsum dolor sit amet. Donec eu nunc nec nibh http://www.somesite.com/somefolder/blahblah/etc/something.txt. Lorem ipsum dolor sit amet. Donec eu nunc nec nibh http://www.somesite.com/somefolder/blahblah/etc/something.doc.';
preg_match_all('#\b(http://\S+\.txt)\b#', $str, $m);

说明:

#             : regex delimiter
\b            : word boundary
(             : begin capture group
http://       : litteral http://
\S+           : one or more non space
\.            : a dot
txt           : litteral txt
)             : end capture group
\b            : word boundary
#             : regex delimiter
相关问题