如何根据子字符串的位置替换子字符串?

时间:2018-10-10 19:52:10

标签: php

我想将#@this is a string&%更改为.this is a string*

这是我尝试过的方法,但是不起作用:

$content = "...this is a string...";

$new = str_replace("/[^#@](.*)[^&%]/", "/[^'.'](.*)[^'*']/", $content);

echo $new;

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

str_replace不支持正则表达式参数,您可以改用preg_replace,即:

$content = "#@this is a string..";
$new = preg_replace( "/^#@(.*?)\.\.$/i", '.$1*', $content );
# .this is a string*

正则表达式说明:

enter image description here


Ideone-Regex101

答案 1 :(得分:0)

您可以使用preg_replace_callback函数

   child c1, c2;

   c1.input();
   c2.output();

这样,您的正则表达式中的每个匹配项都将在函数内部运行,然后您可以根据需要创建一些逻辑来替换。 只需返回您需要的东西即可。

答案 2 :(得分:0)

$pattern = "%^[\.]+(.+[^\.])[\.]+$%";
$str = "...this is a string...";
$new = preg_replace($pattern, '..$1.', $str);


^       from start
[\.]+   dots, 1 or more
(       start subgroup
.+      any char...
[^\.]   ...but not dot
)       subgroup end
[\.]+$  dots, one or more, to the end.