PHP preg_replace

时间:2017-02-22 18:46:59

标签: php regex

给出如下字符串

$text= 'You must call  [[abc\base\Object::
        canGetProperty()|canGetProperty()]] or
        [[abc\base\Object::canSetProperty()|
        canSetProperty()]] respectively.'

我想将其改为

'You must call [canGetProperty()](www.domain.com/
 abc-base-object.html#canGetProperty()) or 
 [canSetProperty()]((www.domain.com/abc-
 base-object.html#canGetProperty()) respectively.'

我试过了:

  $text = 'You must call  [[abc\base\Object::
          canGetProperty()|canGetProperty()]] or 
          [[abc\base\Object::canSetProperty()|
          canSetProperty()]] respectivement.';

  $pattern = '/\[\[(([^\:]+\\\)+[^\:]+)\:\:([^\|]+)\|([^\]]+)\]\]/';
  $replacement = '[$3](www.domain.com/$1.html#$3)';
  echo $text.'<br/>'; //original text
  echo preg_replace($pattern, $replacement, $text);

我得到了

You must call [canGetProperty()](www.domain.com/abc
\base\Object.html#canGetProperty()) or [canSetProperty()]
(www.domain.com/abc\base\Object.html#canSetProperty()) 
respectivement.

除了abc\base\Object没有变成abc-base-object

之外,这与我想要的不远

如何将\替换为-,不知道它出现的时间以及如何将初始大写变为小写?

1 个答案:

答案 0 :(得分:0)

使用preg_replace_callbackstr_replacestrtolower函数的解决方案:

$text = 'You must call  [[abc\base\Object::canGetProperty()|canGetProperty()]] or [[abc\base\Object::canSetProperty()|canSetProperty()]] respectively.';

$pattern = '/\[\[(\w+\\\\\w+\\\\\w+)::(\w+\(\))\|\2\]\]/i';
$new_text = preg_replace_callback($pattern, function($matches){    
    return "[{$matches[2]}]" 
            . "(www.domain.com/" . str_replace("\\", "-", strtolower($matches[1]))
            . ".html#{$matches[2]})";
}, $text);

print_r($new_text);

输出:

You must call  [canGetProperty()](www.domain.com/abc-base-object.html#canGetProperty()) or [canSetProperty()](www.domain.com/abc-base-object.html#canSetProperty()) respectively.