正则表达式内联选项

Gij*_*ijs 1 php regex

我有一个文本已经在文本中有可能的值,我想在情境中显示正确的值.我对正则表达式并不是很好,我真的不知道如何解释我的问题,所以这里有一个例子.我几乎让它工作了:

$string = "This [was a|is the] test!";

preg_replace('/\[(.*)\|(.*)\]/', '$1', $string);
// results in "This was a text!"

preg_replace('/\[(.*)\|(.*)\]/', '$2', $string);
// results in "This is the test!"
Run Code Online (Sandbox Code Playgroud)

这没有问题,但是当有两个部分时它不再起作用,因为它从最后一个获得结束括号.

$string = "This [was a|is the] so this is [bullshit|filler] text";

preg_replace('/\[(.*)\|(.*)\]/', '$1', $string);
//results in "This was a|is the] test so this is [bullshit text"

preg_replace('/\[(.*)\|(.*)\]/', '$2', $string);
//results in "This filler text"
Run Code Online (Sandbox Code Playgroud)

情境1应该是(和|之间的值,而情况2应该显示|和之间的值).

mar*_*rio 5

你的探索是正则表达式的贪婪.添加一个?after .*以使其仅消耗方括号内的字符串:

 preg_replace('/\[(.*?)\|(.*?)\]/', '$1', $string);
Run Code Online (Sandbox Code Playgroud)

同样可以使用/Uungreedy修饰符.更好的是使用更具体的匹配代替.*?任何东西.