gpt4 book ai didi

PHP preg_replace

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:58 26 4
gpt4 key购买 nike

给定如下字符串

$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 之外,这离我想要的不远了


如何将 \ 替换为 - 而不知道它出现的次数以及如何将首字母大写转换为小写?

最佳答案

使用 preg_replace_callback 的解决方案, str_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.

关于PHP preg_replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42399801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com