0

What is the simplest way to change

<a href="link">title</a>

into

[url="link"]title[/url]

Thanks

0

3 Answers 3

2

Offering improved version:
1) will consider both '" as argument enclosures
2) will work with multiple tags
3) allows for other params in the a tag and various spacing

<?php
$r = "<a href=\"test.html\" arg2=\"foo\" bar3=\"_something_else\">test</a>\n
<a href= \"test2.html\" >test2</a>\n
<a href = 'test3.html'>test3</a>\n
";
$r = preg_replace("/<a.*?href[^=]*=[^'\"]*['\"]([^'\"]+)['\"].*?>([^<]+)<\/a>/", "[url=\\1]\\2[/url]", $r);
echo $r;

output:

[url=test.html]test[/url]

[url=test2.html]test2[/url]

[url=test3.html]test3[/url]
Sign up to request clarification or add additional context in comments.

7 Comments

Would it be possible to remove a target="_blank" from the a tag when turning this into the output? That is my problem atm.
Also, I know it's a completely different subject, but when I have <br /> in the html, how can I remove this and make it visually look like new line to the user?
above regex would already strip any other params try yourself ;) it will work
about <br /> -- convert to \n
I don't really understand these expressions. It's [url=link], there are no " ". Can you make the alterations?
|
2

You can try with

$result = preg_replace('/<a href="(.*)">(.*)<\/a>/', '[url="\1"]\2[/url]', $input);

2 Comments

I'm getting the following error with that. Warning: preg_replace() [function.preg-replace]: Unknown modifier 'a'
Sorry, I forgot to escape the slash in </a>. I've just edited my answer.
2

Try using this Expression: #<a href="(.*?)">(.*?)</a>#s.

Example:

$str = '<a href="link">title</a>';
$str = preg_replace( '#<a href="(.*?)">(.*?)</a>#s', '[url="\\1"]\\2[/url]', $str);

Demo: Codepad

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.