如何阻止一个preg替换阵列干扰另一个?

时间:2015-04-02 21:20:30

标签: php arrays preg-replace

function html_url_to_link($string) {

  $patterns = array();
  $patterns[0] = '/user\/(.+)/';
  $patterns[1] = '/http:\/\/(.+)/';

  $replacements = array();
  $replacements[0] = '<a href="/user/$1">user/$1</a>';
  $replacements[1] = '<a href="$0">$0</a>';

  return preg_replace($patterns, $replacements, $string);

}

如果文本为http://website.com/user/account,则第一个数组(0)将干扰第二个数组(1)。

1 个答案:

答案 0 :(得分:0)

我能够通过翻转周围的图案并稍微调整它来实现它的功能:

$patterns = array();
$patterns[] = '/http:\/\/([^\/]+)\//';
$patterns[] = '/user\/(.+)/';

$replacements = array();
$replacements[] = '<a href="$0">$0</a>';
$replacements[] = '<a href="/user/$1">user/$1</a>';

$string = 'http://website.com/user/account';

echo preg_replace($patterns, $replacements, $string);

导致......

<a href="http://website.com/">http://website.com/</a><a href="/user/account">user/account</a>