简体   繁体   中英

Use preg_replace

What is the simplest way to change

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

into

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

Thanks

您可以尝试

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

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

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]

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