duanpin2009 2013-07-31 20:53
浏览 30
已采纳

PHP在字符串中以任何形式查找URL

I'm looking for some form of input security on a project I working on. Basically I wish to flag text if the user has inputted any form of a URL.

IE 'For more of my pic visit myhotpic.net'

Hence it would detect a url and then I can flag the string for validation via staff. So I would need to check for any form of a URL.

There is a similar question here Finding urls from text string via php and regex? with an answer. But I have tired this with various strings and I do not get the expected results.

For example

$pattern = '#(www\.|https?:\/\/){?}[a-zA-Z0-9]{2,254}\.[a-zA-Z0-9]{2,4}(\S*)#i'; $count = preg_match_all($pattern, 'http://www.Imaurl.com', $matches, PREG_PATTERN_ORDER);

returns matches as

array(3) {
  [0]=>
  array(0) {
  }
  [1]=>
  array(0) {
  }
  [2]=>
  array(0) {
  }
}

and no error is return via preg_last_error()

Why is this not working? Is there an error in the Regex? I would assume it to be fine as other users have had success with it.

I cannot seem to find a suitable answer for my problem anywhere else.

  • 写回答

1条回答 默认 最新

  • duangou1551 2013-07-31 21:06
    关注

    In the regex, change {?} to just ?. Then it will work. No idea what {?} is supposed to mean (I've never seen anything like that).

    Your regex will work fine for some URLs, but you should be aware that URLs can be much more complicated than you might assume, and a regex that can match every URL is VERY complex. You might want to look up a better regex—you only need one complicated enough to handle the sorts of URLs you're expecting to match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法