preg_replace [ ] 之间有连字符的空格
preg_replace spaces with hyphens between [ ]
我正在尝试将封闭的 [ ] 变成相关链接。
前任。 [加拿大] = 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="/" class="linked"></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>
谢谢
一次搞定
$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>.
我正在尝试将封闭的 [ ] 变成相关链接。 前任。 [加拿大] = 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="/" class="linked"></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>
谢谢
一次搞定
$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>.