2017-02-22 61 views
3

鑑於像下面PHP的preg_replace

$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


我怎麼能有\取代-不知道它出現的時間的數量,以及如何將首字母大寫什麼遠變成小寫?

回答

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. 
+0

非常感謝你,這是完美的。 – meaulnes

+0

@meaulnes,不客氣 – RomanPerekhrest