简单的任务正则表达式表达式通过测试替换任何“%function test%”

时间:2015-01-06 15:09:01

标签: php regex

我正在尝试找到一个好的表达式来替换以:

开头的任何字符串
"%function

以结尾:

%"

以inbetween字符串为例:

“%function test%”应返回

test 

和“%function test%”,“%function test%”应返回:

test,test

我试过这个

preg_replace('/"%function (.*)?%"/', '$1',$string);

我一开始有很大的希望,因为我的第一个例子很棒,但是功能不是很好。

有关详细信息,您可以查看代码并在此处尝试(一种phpfiddle):http://sandbox.onlinephpfunctions.com/code/00232644b801271e2ffb2ddf4cd450ddffcb50c2

任何帮助将不胜感激, 最好的问候。

3 个答案:

答案 0 :(得分:2)

通过在捕获组外部使用?,您可以选择它。相反,你想要的是一个非贪婪的*,所以你必须这样做。其他选择是([^%]+)

preg_replace('/"%function (.*?)%"/', '$1',$string);

答案 1 :(得分:2)

你可以使用环顾四周

(?<="%function )[^%]+(?=%")

Regex Demo

preg_match_all( "/(?<=\"%function )[^%]+(?=%\")/", "\"%function test%\"", $matches);

将产生

Array ( [0] => Array ( 
                       [0] => test 
                      ) 
      ) 

答案 2 :(得分:0)

%\s*\S+\s+(\S+?)\s*%

试试这个。$1。见。演示。

https://regex101.com/r/wZ0iA3/8

$re = "/%\\s*\\S+\\s+(\\S+?)\\s*%/im";
$str = "%function test%\n%function test%,% function test%";
$subst = "$1";

$result = preg_replace($re, $subst, $str);