1

i write preg match rules:

$subject = 'text  <a href="http://google.com">LINK</a> text text <a href="http://google2.com">LINK2</a>';

$search = array(
    '/\<a href\="(.*)\">(.*)\<\/a\>/i'
);

$replace = array(
    "[a href=\"$1\"]$2[/a]"
);

echo preg_replace($search, $replace, $subject);

When in text only one link everything works great, then more then one - crach code

This i get when is more than one link: "text [a href="http://google.com">LINK text text "

2 Answers 2

2

Change to '/\<a href\="(.*?)\">(.*?)\<\/a\>/i' to make the matching not-greedy.

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

Comments

0

Here's a better regex - it deals with extra fields in the tags:

 \<a (?:.*?)href\=[\"\']([^\"\']+?)[\"\'][^\>]*?\>(.+?)\<\/a\>

I think I've escaped all of the special characters in there, I'm not sure what PHP considers 'special', but basically this should match all of the following:

 $subject = 'text  <a id="test" href="http://google.com">LINK</a> text text <a href="http://google2.com" id="test">LINK2</a> text <a href="http://google3.com">LINK3</a>';

Also, I don't know about PHP, but to match more than one link in Perl, you need the /g modifier on the end of that regex, so:

 $search = array(
      '/\<a (?:.*?)href\=[\"\']([^\"\']+?)[\"\'][^\>]*?\>(.+?)\<\/a\>/ig'
 );

would be your search. Maybe preg_replace does this already, but I'd be surprised, since there are times when you'd only want to replace one instance in your target text.

Comments

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.