我试图将封闭的[]变成相对链接。 防爆。 [加拿大] = Canada
当我在国名中有空格时,我遇到了困难。
这是我的代码:
$text = "[dominican republic] is a country. There are too many hyphens here between square brackets. [canada toronto], and [jamaica]. But none after closed brackets.";
$text = preg_replace_callback("~\[([^\)]*)\]~", function($s) {
return str_replace(" ", "-", "[$s[1]]");
}, $text);
$text = preg_replace('|(?<![!\\\])\[(([^\s\]]+))\]|', '<a href="/$2" class="linked">$2</a>', $text);
print $text;
结果如下:
<p><a href="/dominican-republic" class="linked">dominican-republic</a>-is-a-country.-There-are-too-many-hyphens-here-between-square-brackets.-<a href="/canada-toronto" class="linked">canada-toronto</a>,-and-<a href="/jamaica" class="linked">jamaica</a>. But none after closed brackets.</p>
谢谢
答案 0 :(得分:2)
让我们一次性完成
$text = "[dominican republic] is a country. There are too many hyphens here between square brackets. [canada toronto], and [jamaica].";
$text = preg_replace_callback("~\[([^\]]*)]~", function($s) {
return '<a href="/'.str_replace(" ", "-", $s[1]).'" class="linked">'.$s[1].'</a>';
}, $text);
print $text;
输出:
<a href="/dominican-republic" class="linked">dominican republic</a> is a country. There are too many hyphens here between square brackets. <a href="/canada-toronto" class="linked">canada toronto</a>, and <a href="/jamaica" class="linked">jamaica</a>.