Is there a conditional preg_replace in PHP?

I have code like this that replaces some shortcodes with a link:

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

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

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

I have many more similar ones, so I was wondering if there is a way to reduce this to a simple simple preg_replacewith a conditional?

For example, use regex #\{([a-z])\|([^|]+)\|([^}]+)\}#and replace the first match with something else (r = ref, t = type) based on its letter? (If that helps, shortcodes are similar to {r|url-slug|LinkTitle}.)

+5
source share
2 answers

This calls preg_replace_callback(or perhaps only the /eeval modifier ), which allows you to put the t= typeand r= mapping refin the replacement logic:

= 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>";
}
+9
source

: 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 , \' .

,

, , , , 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>

,

+3

All Articles