简体   繁体   English

preg_match模式匹配表达式以获取PHP中的URL

[英]preg_match pattern-matching expression to get URL in php

I have a text as follows : 我的案文如下:
I have this text 'The text (is in parenthesis) ends' 我有这个文字“(括号中的)文字结束”
here: www.url1.com 此处:www.url1.com
and here: some text (www.url2.com) 此处:一些文字(www.url2.com)

I want to extract www.url2.com and store in a variable. 我想提取www.url2.com并存储在变量中。
I am using the pattern : preg_match('/(?<=()(.+)(?=))/is', $message, $match); 我正在使用模式:preg_match('/(?<=()(.+)(?=))/ is',$ message,$ match);
This fails cause of the parenthesis in line 1. 这导致第1行中出现括号的原因失败。
The string extracted is : is in parenthesis) 提取的字符串是: 位于括号中)
Please help me by providing a suitable regex expression. 请提供合适的正则表达式来帮助我。

if (preg_match('/\(\s?(www\.\w+\.com)\s?\)/', $text, $matches)){
    $var = $matches[1];
}

That assumes .com . 假设.com If you want to allow, for example, .net and .org , you can modify it as: 如果要允许使用例如.net.org ,则可以将其修改为:

if (preg_match('/\(\s?(www\.\w+\.(com|net|org))\s?\)/', $text, $matches)){
    $var = $matches[1];
}
preg_match("#\((www\.[^\s]+)\)#", $text, $match);

echo $match[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM