2

I have some text, and I need to wrap my site urls into links.

Example text: "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"

I need to match these URLs:

  • 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

I have ((\S+|\s)vitasya-le.work(\s|\S+|$)) pattern but it doesn't match all combinations

1
  • Eh, .vitasya-le.work is not a valid URL... Commented Oct 22, 2014 at 10:19

2 Answers 2

1

Here is a regex that should match all of them:

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

And some tests:

$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));
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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

Steps:

  • optionally match http:// optionally followed by www., or just .
  • then match the main part of the URL
  • match any sequence of characters after the main part that aren't space characters

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.