2012-03-07 22 views
5

我有一些这样的代码,它取代了一些简码的链接:PHP中是否有条件的preg_replace?

$search = array(
    '#\{r\|([^|]+)\|([^}]+)\}#', 
    '#\{t\|([^|]+)\|([^}]+)\}#', 
    ..., 
); 

$replace = array(
    '<a href="/ref/$1">$2</a>', 
    '<a href="/type/$1">$2</a>', 
    ..., 
); 

$content = preg_replace($search, $replace, $content); 

我是相似的,所以我想知道其它更多的,是有一些方法来减少这一个简单的preg_replace与条件?

例如,使用正则表达式#\{([a-z])\|([^|]+)\|([^}]+)\}#并根据字母替换第一个匹配项(r = ref,t = type)? (如果有帮助,在简码像{r|url-slug|LinkTitle}。)

回答

9

这就要求preg_replace_callback(或可能只是/e EVAL修改),这将让你把映射t = type和更换逻辑r = ref

= preg_replace_callback('#\{([rt])\|([^|]+)\|([^}]+)\}#', "cb_123", ... 

function cb_123($m) { 

    $map = array("t" => "type", "r" => "ref"); 
    $what = $map[ $m[1] ]; 

    return "<a href=\"/$what/$m[2]\">$m[3]</a>"; 
} 
3

免责声明:什么下面下面是可怕的建议,并建议使用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&amp;' with some bad characters in it</a> and a type <a href="/ref/link2.php">link with some &quot;quotes&quot; in it</a>

See it working