PHP正则表达式与特定的站点URL匹配params

时间:2014-10-22 09:54:30

标签: php regex url

我有一些文字,我需要将我的网站网址包装成链接。

示例文本:" Lorem ipsum dolor sit amet,vitasya-le.work consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 http://vitasya-le.work Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。 habrahabr Duis aute irure dolor in repreptderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 vitasya-le.work"

我需要匹配这些网址:

  • http://vitasya-le.work
  • vitasya-le.work
  • http://www.vitasya-le.work
  • vitasya-le.work/topic/view/33113-topic-title
  • http://vitasya-le.work/topic/view/33113-topic-title
  • http://www.vitasya-le.work/topic/view/33113-topic-title
  • .vitasya-le.work

我有((\S+|\s)vitasya-le.work(\s|\S+|$))模式,但它并不匹配所有组合

2 个答案:

答案 0 :(得分:1)

这是一个应该匹配所有这些的正则表达式:

$regex = '/(?:http:\/\/)?(?:www\.)?vitasya-le\.work(?:\/[\w\-]+)*\/?/';

还有一些测试:

$tests = array(
    'http://vitasya-le.work',
    'vitasya-le.work',
    'http://www.vitasya-le.work',
    'vitasya-le.work/topic/view/33113-topic-title',
    'http://vitasya-le.work/topic/view/33113-topic-title',
    'http://www.vitasya-le.work/topic/view/33113-topic-title',
);
echo '<pre>';
foreach ($tests as $test) {
    preg_match($regex, $test, $match);
    if (empty($match)) {
        echo 'Did NOT match: ', $test, "\n";
    } else {
        echo 'Match: ', $test, "\n";
    }
}

$test2 = 'Lorem ipsum dolor sit amet, vitasya-le.work consectetur '
.'adipiscing elit, sed do eiusmod tempor incididunt ut labore '
.'et dolore magna aliqua. http://vitasya-le.work Ut enim ad '
.'minim veniam, quis nostrud exercitation ullamco laboris nisi '
.'ut aliquip ex ea commodo consequat. habrahabr Duis aute irure '
.'dolor in reprehenderit in voluptate velit esse cillum dolore '
.'eu fugiat nulla pariatur. vitasya-le.work';

preg_match_all($regex, $test2, $matches);
var_dump(array_pop($matches));

答案 1 :(得分:0)

试试这个:

$text = preg_replace(
    '/((http:\/\/(www.)?|\.))?vitasya-le\.work[\S]*/',
    '<a href="$0">$0</a>',
    $text
);

步骤:

  • 可选地匹配http://,可选地后跟www.,或仅.
  • 然后匹配网址的主要部分
  • 匹配主要部分之后没有空格字符的任何字符序列