通过php和regex从文本字符串中查找网址?

Sis*_*sir 5 php regex preg-replace preg-match-all

我知道问题标题看起来非常重复.但是我在这里找不到一些解决方案.

我需要找到url表单文本字符串:

$pattern = '`.*?((http|https)://[\w#$&+,\/:;=?@.-]+)[^\w#$&+,\/:;=?@.-]*?`i';

    if (preg_match_all($pattern,$url_string,$matches)) {
        print_r($matches[1]);
    }
Run Code Online (Sandbox Code Playgroud)

使用这种模式我能找到的网址http://https://这是好.但我有用户输入,人们www.domain.com甚至可以添加网址domain.com

所以,我需要首先验证字符串,然后我可以用它们之前的www.domain.com domain.com常规协议替换http://它.或者我需要提出更好的模式?

我对正则表达不太好,不知道该怎么做.

我的想法是首先找到的网址http://,并https://在把它们放在一个数组,然后替换这些URL以空格("")的文本字符串,然后使用其他模式来进行的.但我不确定使用什么模式.

我正在使用这个,$url_string = preg_replace($pattern, ' ', $url_string );但是删除两个有效网址之间的任何www.domain.comdomain.com网址http://https://

如果你能提供帮助就会很棒.

为了使事情更清楚:

我需要一个模式或其他方法,我可以在文本中找到所有网址.url的例子是:

  1. domain.com
  2. www.domain.com
  3. http://www.domain.com
  4. http://domain.com
  5. https://www.domain.com
  6. https://domain.com

谢谢!5.

Adr*_*n B 3

$pattern = '#(www\.|https?://)?[a-z0-9]+\.[a-z0-9]{2,4}\S*#i';
preg_match_all($pattern, $str, $matches, PREG_PATTERN_ORDER);
Run Code Online (Sandbox Code Playgroud)