给出如下字符串
$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 :(得分:0)
使用preg_replace_callback,str_replace
和strtolower
函数的解决方案:
$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.