新手又有正则问题需要请教!

WBOY
Release: 2016-06-23 13:55:55
Original
883 people have browsed it

新手,在打书上的文章发布工具时,用正则匹配URL出了点问题。

$pattern = '/(http\:\/\/|https\:\/\/)?([a-zA-Z0-9-]+\.)+(com|cn|org|net)(\/[\w\%\&\=\'\"\?\/\.]*)?/';$string = 'http://demo.demo.baidu.com';preg_match_all($pattern,$string,$result);
Copy after login

遍历$result的结果是
[code=php]
Array
(
[0] => Array
(
[0] => http://demo.demo.baidu.com
)
[1] => Array
(
[0] => http://
)

[2] => Array
(
[0] => baidu.
)
[3] => Array
(
[0] => com
)
[4] => Array
(
[0] =>
)
)
[/php]
第二个子表达式其实是匹配了’www.‘以及’baidu.‘,有两次匹配,但是返回的结果里只有一处匹配T.T
整个表达式是能够匹配整个URL的,但是我要用到第二个子表达式的两次匹配结果,现在只有一个,望各位指教问题出现在哪儿!
感谢!


回复讨论(解决方案)

(http\:\/\/|https\:\/\/)?(([a-zA-Z0-9-]+\.)+)+(com|cn|org|net)(\/[\w\%\&\=\'\"\?\/\.]*)?
Copy after login

楼上大神解决。不过我感觉第二个子表达式后面不用加+

(http\:\/\/|https\:\/\/)?(([a-zA-Z0-9-]+\.)+)(com|cn|org|net)(\/[\w\%\&\=\'\"\?\/\.]*)?
Copy after login

$pattern = '/(http\:\/\/|https\:\/\/)?((?:[a-zA-Z0-9-]+\.)+)(com|cn|org|net)(\/[\w%&=\'"?\/.]*)?/';$string = 'http://demo.demo.baidu.com';preg_match_all($pattern,$string,$result);
Copy after login
Array(    [0] => Array        (            [0] => http://demo.demo.baidu.com        )    [1] => Array        (            [0] => http://        )    [2] => Array        (            [0] => demo.demo.baidu.        )    [3] => Array        (            [0] => com        )    [4] => Array        (            [0] =>         ))
Copy after login

其实我是想用做一个URL添加a标签的函数,要用preg_replace()结合模式修正符e,在replacement参数里要调用到一个函数,给这个函数传入匹配到的字符串也就是URL,书上写的是urlCut('\\1\\2\\3\\4'),我不熟悉也就跟着用这个方法传入了。一开始就出现了最上面那个问题。用了上面大神的方法解决之后是没问题的,但是大神提醒查了手册之后,发现可以直接传入\\0,这也就省了很多事了。万万没想到啊~
再次感谢二位!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!