简体   繁体   中英

PHP - regexp to split URLs

I have a text with " a href " and " [link] " links. I want to preg_split this text and have array where on [i] I can found links

Example:

My text <a href="www.example.com">text</a> this continues [link=http://www.second.com]link[/link]

=>

[0] My text
[1] <a href="www.example.com">text</a>
[2] this continues
[3] [link=http://www.second.com]link[/link]

How should I wrote my regexp?

(.+)(\\<a.+\\/a>)(.+)(\\[link.+\\/link])

produces

Match groups:
1.  My text
2.  <a href="www.example.com">text</a>
3.  this continues
4.  [link=http://www.second.com]link[/link]

http://rubular.com/r/8PEUbDX9zr

Something like this i guess. Assuming everything is on the same line..

/\<a\.*[link=(.*)\].*$/i
<?php
$text = 'My text <a href="www.example.com">text</a> this continues [link=http://www.second.com]link[/link]';


preg_match_all('/(?:href="|link=)(.*?)(?:"|\])/is', $text, $links);
// $links[1] = array('link', 'link', 'link'...)
$links = $links[1]; // $links = array('link'...)
?>

Should work :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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