0

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?

1
  • Don't parse HTML with regular expressions. Use the DOM module that comes with PHP. Regular expressions are not always the tool to use, even if the problem involves text. Commented Dec 2, 2012 at 15:40

3 Answers 3

1

(.+)(\<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

Sign up to request clarification or add additional context in comments.

Comments

0

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

/\<a\.*[link=(.*)\].*$/i

Comments

0
<?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 :)

3 Comments

It returns only [0] => www.example.com
If I copy my example straight off and run it and var_dump $links I get [0] => "www.example.com" [1] => "second.com" Sure you are using preg_match_all?
Strange.. If I copy & paste your example, I got only what I posted... and even your output is different from what I needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.