免责声明:什么下面下面是可怕的建议,并建议使用PHP的功能,是相当正确地现在已经过时的。我只是把它留在这里作为历史参考。
使用接受的答案中建议的技巧。
的替代(完全有效)preg_replace_callback()
方法通过@mario建议是e
改性剂,这是仅适用于preg_replace()
,并允许替换字符串被评价为PHP代码:
<?php
$shortCodes = array (
'r' => 'ref',
't' => 'type'
);
$expr = '#\{([a-z])\|([^|]+)\|([^}]+)\}#e';
$replace = '"<a href=\"/{$shortCodes[\'$1\']}/$2\">$3</a>"';
$string = 'Some text as a ref {r|link1.php|link} and a type {r|link2.php|link}';
echo preg_replace($expr, $replace, $string);
我能想到的唯一问题是如果您的LinkTitle
包含单引号,它将被转义并在输出中显示为\'
。
See it working
编辑
一个小试验和错误后,这里是有什么工作,你可以扔了一个版本,并通过urlencode()
/htmlspecialchars()
酌情通过了所有的数据:
<?php
$shortCodes = array (
'r' => 'ref',
't' => 'type'
);
$expr = array(
'#\{([a-z])\|([^|]+)\|([^}]*"[^}]*)\}#e',
'#\{([a-z])\|([^|]+)\|([^}]+)\}#e'
);
$replace = array(
'"<a href=\"/{$shortCodes[\'$1\']}/".htmlspecialchars(urlencode(\'$2\'))."\">".htmlspecialchars(str_replace(\'\"\', \'"\', \'$3\'))."</a>"',
'"<a href=\"/{$shortCodes[\'$1\']}/".htmlspecialchars(urlencode(\'$2\'))."\">".htmlspecialchars(\'$3\')."</a>"'
);
$string = 'Some text as a ref {r|link &1.php|link&\' with some bad characters in it} and a type {r|link2.php|link with some "quotes" in it}';
echo preg_replace($expr, $replace, $string);
输出:
Some text as a ref <a href="/ref/link+%261.php">link&' with some bad characters in it</a> and a type <a href="/ref/link2.php">link with some "quotes" in it</a>
See it working