4

I'm trying to extract URL from a piece of string I have different posts that contains URL in their message. I've prepared a pattern to match but it's not working properly.

Tried Regex

$pattern1= '%\b((https?://)|(www\.)|(^[\D]+\.))[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))%';
$pattern2= '%\b^((https?://)|(www\.)|(^[a-z]+\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%';

CODE

for ( $i = 0; $i < $resultcount; $i ++ ) {
    $pattern = '%\b^((https?://)|(www\.)|(^[a-z]+\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%';
    $message = (string)$result[$i]['message'];
    preg_match_all($pattern,$message,$match);
    print_r($match);
    }

A Example of my post like this

"This is just a post to test regex for extracting URL http://google.com, https://www.youtube.com/watch?v=dlw32af https://instagram.com/oscar/ en.wikipedia.org"

Post may have comma or may not have comma for multiple URLs

Thank you people :)

2 Answers 2

7

This should get you started:

\b(?:https?://)?(?:(?i:[a-z]+\.)+)[^\s,]+\b


Broken down, this says:

\b                   # a word boundary
(?:https?://)?       # http:// or https://, optional
(?:(?i:[a-z]+\.)+)   # any subdomain before
[^\s,]+              # neither whitespace nor comma
\b                   # another word boundary

See a demo on regex101.com.

Sign up to request clarification or add additional context in comments.

3 Comments

hey thanks but I need to extract all URLs mentioned.. Could help me for this?
yeah it's works like charm but if the urls has ',' then it's taking all urls into one any fix for comma separated urls?
@Mr.Pyramid: Check the newly updated answer - please put your requirements more clearly in the first place :) regex101.com/r/9hhKLS/3
0

First I am analyse some URL of wikipedia which is clearly show in attach screenshot then write regex !

https:\/\/en.wikipedia.org\/wiki\/(.*) 

enter image description here

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.