用正则表达式替换所选字符串


Replace in string selected with regex

我有相当大的txt文件,我想在用正则表达式选择的字符串中使用替换。

文件填充了多行,如下所示:

...||date|14.02.2010||interest|games and books||options|opt1, opt2 and opt3||age|24||...

现在在|options|opt1, opt2 and opt3|我想将and更改为,,使其看起来像|options|opt1, opt2, opt3|

我认为这应该像这样工作:

  1. 选择带有正则表达式的字符串,例如。 '|options'|(.*?)'|
  2. 现在像这样:在$1中将and替换为,

并重复多次。

如何在 PHP 中做到这一点?我希望这已经足够清楚了。

怎么样:

$str = '...||date|14.02.2010||interest|games and books||options|opt1, opt2 and opt3||age|24||...';
$str = preg_replace('/('|options'|[^|]*) and/', "$1,", $str);
echo $str,"'n";

输出:

...||date|14.02.2010||interest|games and books||options|opt1, opt2, opt3||age|24||...

试试这个

$str= preg_replace('/('|options'|[^|]+) and /', ''1,', $str);