匹配正则表达式不起作用

时间:2014-01-28 09:54:06

标签: php regex preg-match

在这一个小时,有人可以帮忙吗?

尝试匹配以便从这种输入中获取一个网址:

www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htmwww.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htmwww.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htmwww.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm

取自文本框。

<form action="" method="post">
    <textarea name="urls"></textarea>
    <input type="submit">
</form>
<?php
if(preg_match("/[^www]{3}.[a-zA-Z0-9\/\._]+\/\.htm$/", $_POST['urls'], $matches))
{
    echo 'yay';
}

?>

我想从preg_match得到的是:www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm

4 个答案:

答案 0 :(得分:1)

您可以使用这个简单的正则表达式:

w{3}.+htm

整个命令:

preg_match("/w{3}.+htm/", $_POST['urls'], $matches)

Online Test

答案 1 :(得分:0)

尝试:preg_match("/^w{3}.[a-zA-Z0-9\/\._]+\.htm$/", $_POST['urls'], $matches)

答案 2 :(得分:0)

您可以使用正则表达式进行拆分:

$links = preg_split("/(?=www\.)/", "www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htmwww.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htmwww.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htmwww.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm");
print_r($links);

(?=www\.)lookahead assertion,当有“www”时会匹配。在字符串中前进。

输出:

Array ( [0] => [1] => www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm 
               [2] => www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm 
               [3] => www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm 
               [4] => www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm )

答案 3 :(得分:0)

尝试:

(w{3}.+?\.htm)

See it in action